1. Trang chủ
  2. » Công Nghệ Thông Tin

Thực hành sử dụng XML trong Java Lab 6

10 180 0

Đang tải... (xem toàn văn)

THÔNG TIN TÀI LIỆU

Thông tin cơ bản

Định dạng
Số trang 10
Dung lượng 584,61 KB

Các công cụ chuyển đổi và chỉnh sửa cho tài liệu này

Nội dung

IT Research Department @BKAP 2015 Page 1 / 10Lab 06 XML and Databases Mục tiêu - Phân tích file XML và lấy nội dung file XML đẩy vào SQL Database - Truy nhập SQL Database lấy dữ liệu g

Trang 1

IT Research Department @BKAP 2015 Page 1 / 10

Lab 06 XML and Databases Mục tiêu

- Phân tích file XML và lấy nội dung file XML đẩy vào SQL Database

- Truy nhập SQL Database lấy dữ liệu ghi ra file XML theo định dạng template-based

- Sử dụng Xquery phân tích file XML

Phần I Bài tập step by step

Bài 6.1 Phân tích nội dung file Employees.xml và đẩy nội dung file vào bảng EMPLOYEE:

 Employees.xml

 Output:

Trang 2

IT Research Department @BKAP 2015 Page 2 / 10

Step 1: Tạo project java mới trong netbean

 File  New Project  Java  Java Application

 Project Name: Đặt tên Project là XMLDatabase

Step 2: Tạo File Employees.xml

 Project  New  Other  XML  XML Document

 Employees.xml

<?xml version="1.0" encoding="UTF-8"?>

<employees>

<employee id="111">

<firstname>Allen</firstname>

<lastname>Smith</lastname>

<location>Alaska</location>

<gender>M</gender>

</employee>

<employee id="112">

<firstname>John</firstname>

<lastname>Davis</lastname>

<location>Kansas</location>

<gender>M</gender>

</employee>

<employee id="113">

<firstname>Bob</firstname>

<lastname>Thomson</lastname>

<location>Kansas</location>

<gender>M</gender>

</employee>

</employees>

Step 3: Tạo bảng EMPLOYEE trong database SQL 2012

CREATE TABLE [dbo].[EMPLOYEES](

[ID] [nvarchar](50) primary key NOTNULL,

[FIRSTNAME] [nvarchar](50)NULL,

[LASTNAME] [nvarchar](50)NULL,

[LOCATION] [nvarchar](50)NULL,

[GENDER] [nvarchar](50)NULL)

Trang 3

IT Research Department @BKAP 2015 Page 3 / 10

Step 4: Triển khai hàm main của ứng dụng

 XMLDatabase.java

package xmldatabase;

import java.io.File;

import java.io.IOException;

import java.sql.Connection;

import java.sql.DriverManager;

import java.sql.PreparedStatement;

import java.sql.SQLException;

import javax.xml.parsers.DocumentBuilder;

import javax.xml.parsers.DocumentBuilderFactory;

import javax.xml.parsers.ParserConfigurationException;

import org.w3c.dom.Document;

import org.w3c.dom.Element;

import org.w3c.dom.Node;

import org.w3c.dom.NodeList;

import org.xml.sax.SAXException;

/**

*

* @author DELL

*/

publicclass XMLDatabase {

/**

* @param args the command line arguments

*/

publicstaticvoid main(String[] args) throws ParserConfigurationException, SAXException, IOException,

ClassNotFoundException, InstantiationException, IllegalAccessException, SQLException {

//Parsing the XML document

File xmlFile = new File("Employees.xml");

DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();

DocumentBuilder builder = factory.newDocumentBuilder();

Document doc = builder.parse(xmlFile);

doc.getDocumentElement().normalize();

NodeList nodeList = doc.getElementsByTagName("employee");

// Connecting to database

String URL = "jdbc:sqlserver://localhost:1433;databaseName=Struts2";

String DB_DRIVER = "com.microsoft.sqlserver.jdbc.SQLServerDriver";

String user_db = "sa";

String pass_db = "Gacon1984";

Connection conn = null;

Class.forName(DB_DRIVER);

conn = DriverManager.getConnection(URL, user_db, pass_db);

String query = "INSERT INTO employees(id,firstname,lastname,location,gender) values (?,?,?,?,?)";

PreparedStatement prest = null;

prest = conn.prepareStatement(query);

// Retrieving data from XML nodes and storing in the table columns

for (int i = 0; i < nodeList.getLength(); i++) {

Node node = nodeList.item(i);

if (node.getNodeType() == Node.ELEMENT_NODE) {

Element element = (Element) node;

prest.setString(1, element.getAttribute("id"));

Trang 4

IT Research Department @BKAP 2015 Page 4 / 10

prest.setString(2, element.getElementsByTagName("firstname").item(0).getTextContent());

prest.setString(3, element.getElementsByTagName("lastname").item(0).getTextContent());

prest.setString(4, element.getElementsByTagName("location").item(0).getTextContent());

prest.setString(5, element.getElementsByTagName("gender").item(0).getTextContent());

prest.execute();

}

}

conn.close();

}

}

Step 5: Build and Run ứng dụng

Bài 6.2 Lấy dữ liệu từ bảng EMPLOYEES trong SQL Database ghi ra file employees.xml từ file template-based EmployeeInfo.xml

 Input

 EmployeeInfo.xml

 Table EMPLOYEES

Trang 5

IT Research Department @BKAP 2015 Page 5 / 10

 Output

Step 1: Tạo file EmployeeInfo.xml

<?xml version="1.0" encoding="UTF-8"?>

<EmployeeInfo>

<Introduction>List of employees</Introduction>

<SelectStmnt>SELECT id,firstname,lastname,location FROM employees</SelectStmnt>

<employee>

<firstName>$firstName</firstName>

<lastName>$lastName</lastName>

<location>$location</location>

</employee>

<Conclusion>End of employeelist</Conclusion>

</EmployeeInfo>

Step 2: Lấy bảng EMPLOYEE trong bài 6.1 đã làm

Step 3: Tạo JavaMain trong project bài 6.1(XMLDatabase)

 TemplateBase.java

Trang 6

IT Research Department @BKAP 2015 Page 6 / 10

package xmldatabase;

import java.io.File;

import java.io.IOException;

import java.sql.Connection;

import java.sql.DriverManager;

import java.sql.ResultSet;

import java.sql.SQLException;

import java.sql.Statement;

import javax.xml.parsers.DocumentBuilder;

import javax.xml.parsers.DocumentBuilderFactory;

import javax.xml.parsers.ParserConfigurationException;

import javax.xml.transform.Transformer;

import javax.xml.transform.TransformerConfigurationException;

import javax.xml.transform.TransformerException;

import javax.xml.transform.TransformerFactory;

import javax.xml.transform.dom.DOMSource;

import javax.xml.transform.stream.StreamResult;

import org.w3c.dom.Document;

import org.w3c.dom.Element;

import org.w3c.dom.Node;

import org.w3c.dom.NodeList;

import org.xml.sax.SAXException;

/**

*

* @author DELL

*/

publicclass TemplateBase {

/**

* @param args the command line arguments

*/

publicstaticvoid main(String[] args) throws ParserConfigurationException, SAXException, IOException,

ClassNotFoundException, SQLException, TransformerConfigurationException, TransformerException {

//parse file EmployeeInfo and get value query

File file = new File("EmployeeInfo.xml");

DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();

DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();

Document doc = documentBuilder.parse(file);

doc.getDocumentElement().normalize();

NodeList nodeList = doc.getElementsByTagName("EmployeeInfo");

Node node = nodeList.item(0);

Element eElement = (Element) node;

String query = eElement.getElementsByTagName("SelectStmnt").item(0).getTextContent();

//connect database and get data from database to resultset

String URL = "jdbc:sqlserver://localhost:1433;databaseName=Struts2";

String DB_DRIVER = "com.microsoft.sqlserver.jdbc.SQLServerDriver";

String user_db = "sa";

String pass_db = "Gacon1984";

Class.forName(DB_DRIVER);

Connection conn = DriverManager.getConnection(URL,user_db,pass_db);

Statement statement = conn.createStatement();

ResultSet rs = statement.executeQuery(query);

//write from resultset to file xml

Trang 7

IT Research Department @BKAP 2015 Page 7 / 10

Document docxml = documentBuilder.newDocument();

//create root element EmployeeInfo

Element rootElement = docxml.createElement("EmployeeInfo");

docxml.appendChild(rootElement);

//create element Introduction

String itdText= eElement.getElementsByTagName("Introduction").item(0).getTextContent();

Element introduction = docxml.createElement("Introduction");

introduction.appendChild(docxml.createTextNode(itdText));

rootElement.appendChild(introduction);

while (rs.next()) {

//create element employee

Element employee = docxml.createElement("employee");

employee.setAttribute("id", rs.getString("id"));

//create element firstName,lastName,location of element employee

Element firstname = docxml.createElement("firstName");

firstname.appendChild(docxml.createTextNode(rs.getString("firstname")));

Element lastname = docxml.createElement("lastName");

lastname.appendChild(docxml.createTextNode(rs.getString("lastname")));

Element location = docxml.createElement("location");

location.appendChild(docxml.createTextNode(rs.getString("location")));

employee.appendChild(firstname);

employee.appendChild(lastname);

employee.appendChild(location);

//add employee to root element

rootElement.appendChild(employee);

}

//create element Conclusion

String cText= eElement.getElementsByTagName("Conclusion").item(0).getTextContent();

Element conclusion = docxml.createElement("Conclusion");

conclusion.appendChild(docxml.createTextNode(cText));

rootElement.appendChild(conclusion);

//write file employee.xml

TransformerFactory tfactory = TransformerFactory.newInstance();

Transformer tranformer = tfactory.newTransformer();

DOMSource source = new DOMSource(docxml);

StreamResult result = new StreamResult(new File("employees.xml"));

tranformer.transform(source, result);

}

}

Step 4: Build and Run File TemplateBase.java

Trang 8

IT Research Department @BKAP 2015 Page 8 / 10

Bài 6.3

 Sử dụng Xquery in ra màn hình:

 Tất cả giá trị element firstName trong file employees.xml sinh ra trong bài 6.2

 Tất cả giá trị element firstName có location là Kansas trong file employee.xml

Step 1: Tạo java main class trong project XMLDatabase

 XMLBased.java

package xmldatabase;

import java.io.File;

import java.io.IOException;

import javax.xml.parsers.DocumentBuilder;

import javax.xml.parsers.DocumentBuilderFactory;

import javax.xml.parsers.ParserConfigurationException;

import javax.xml.xpath.XPath;

import javax.xml.xpath.XPathConstants;

import javax.xml.xpath.XPathExpressionException;

import javax.xml.xpath.XPathFactory;

import org.w3c.dom.Document;

import org.w3c.dom.NodeList;

import org.xml.sax.SAXException;

/**

*

* @author DELL

Trang 9

IT Research Department @BKAP 2015 Page 9 / 10

*/

publicclass XMLBased {

/**

* @param args the command line arguments

*/

publicstaticvoid main(String[] args) throws ParserConfigurationException, SAXException, IOException,

XPathExpressionException {

//parse file employees.xml with DOM

DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();

DocumentBuilder builder = factory.newDocumentBuilder();

Document doc = builder.parse(new File("employees.xml"));

//create Xpath

XPathFactory xFactory = XPathFactory.newInstance();

XPath xPath = xFactory.newXPath();

//Xquery select all firstName

String expression1 = "/EmployeeInfo/employee/firstName";

System.out.println(expression1);

//get NodeList with expression1

NodeList nodelist1 = (NodeList) xPath.compile(expression1).evaluate(doc,XPathConstants.NODESET);

//print all firstName with expression1

for (int i = 0; i < nodelist1.getLength(); i++) {

System.out.println(nodelist1.item(i).getFirstChild().getNodeValue());

}

//Xquery select firstName with location = Kansas

String expression2 = "/EmployeeInfo/employee[location='Kansas']/firstName";

System.out.println(expression2);

//get NodeList with expression2

NodeList nodelist2 = (NodeList) xPath.compile(expression2).evaluate(doc,XPathConstants.NODESET);

//print all firstName with expression2

for (int j = 0; j < nodelist2.getLength(); j++) {

System.out.println(nodelist2.item(j).getFirstChild().getNodeValue());

}

}

}

Step 2: Build and Run File

Phần II: Bài tập tự làm

Phân tích file HangHoa.xml lấy nội dung file đưa vào table PRODUCT trong database

Trang 10

IT Research Department @BKAP 2015 Page 10 / 10

Ngày đăng: 07/05/2018, 16:20

TỪ KHÓA LIÊN QUAN

w