IT Research Department @BKAP 2015 Trang 1 / 15 Lab 03 Extensible Stylesheet Transformation Language Mục tiêu - Sử dụng transformer chuyển đổi file xml và xsl html - Sử dụng XPath Expr
Trang 1IT Research Department @BKAP 2015 Trang 1 / 15
Lab 03 Extensible Stylesheet Transformation Language
Mục tiêu
- Sử dụng transformer chuyển đổi file xml và xsl (html)
- Sử dụng XPath Expression để lấy dữ liệu theo Expression từ file xml
- Sử dụng JAXP APIs trong quá trình xử lý XPath
Phần I Bài tập step by step
Bài 3.1
In nội dung file emp.xsl chuyển đổi từ file Employees.xml:
Employees.xml
Emp.xsl
Trang 2Step 1: Tạo project java mới trong netbean
File New Project Java Java Application
Project Name: Đặt tên Project là ESTLExample
Step 2: Tạo File Employees.xml
Project New Other XML XML Document
Employees.xml
<?xml version="1.0" encoding="UTF-8"?>
<!
To change this license header, choose License Headers in Project Properties
To change this template file, choose Tools | Templates
and open the template in the editor
>
<employees>
<employeeid="111">
<firstname>Allen</firstname>
<lastname>Smith</lastname>
<location>Alaska</location>
<gender>M</gender>
Trang 3IT Research Department @BKAP 2015 Trang 3 / 15
</employee>
<employeeid="112">
<firstname>John</firstname>
<lastname>Davis</lastname>
<location>California</location>
<gender>M</gender>
</employee>
<employeeid="113">
<firstname>Bob</firstname>
<lastname>Thomson</lastname>
<location>Kansas</location>
<gender>M</gender>
</employee>
</employees>
Step 3: Tạo File emp.xsl
Project New Other XML XSL Stylesheet
Emp.xsl
<?xml version="1.0" encoding="UTF-8"?>
<!
Document : emp.xsl
Created on : February 29, 2016, 9:22 AM
Author : DELL
Description:
Purpose of transformation follows
>
<xsl:stylesheetxmlns:xsl="http://www.w3.org/1999/XSL/Transform"
version="1.0">
<xsl:outputmethod="html"/>
<xsl:variablename = "fName"select="employees/employee/firstname"/>
<! TODO customize transformation rules
syntax recommendation http://www.w3.org/TR/xslt
>
<xsl:templatematch="/">
<html>
<head>
Trang 4<title>XML Data</title>
</head>
<body>
<xsl:iftest ="contains($fName,'Allen')">
<br/>
Admin Employee <br/>
<br/>
<xsl:value-ofselect="employees/employee/firstname"/>
<br/>
<xsl:value-ofselect="employees/employee/lastname"/>
</xsl:if>
</body>
</html>
</xsl:template>
</xsl:stylesheet>
Step 4: Tạo lớp TransformDOM.java để chuyển đổi XML với XSL
TransformDOM.java
package estlexample;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;
import org.w3c.dom.Document;
/**
*
* @author DELL
*/
publicclass TransformDOM {
publicstaticvoid TransformXMLToXsl(Document doc) {
try {
//Create Dom Source
DOMSource source = new DOMSource(doc);
//Create Transformer Factory
TransformerFactory transformerFactory =
TransformerFactory.newInstance();
//Print the type of XSLT processor implemented
Trang 5IT Research Department @BKAP 2015 Trang 5 / 15
System.out.println(transformerFactory.getClass());
//Create Transformer from Transformer Factory - Applying the stylesheet
in the transformation
Transformer tranformer = transformerFactory.newTransformer(new
StreamSource("emp.xsl"));
//An object to hold the results
StreamResult result = new StreamResult(System.out);
tranformer.transform(source, result);
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
Cấu trúc project sau khi hoàn thành
Step 5: Triển khai hàm main của ứng dụng
ESTLExample.java
package estlexample;
import java.io.File;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
/**
*
* @author DELL
*/
publicclass ESTLExample {
/**
* @param args the command line arguments
Trang 6*/
publicstaticvoid main(String[] args) {
try {
File file = new File("Employees.xml");
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setNamespaceAware(true);
DocumentBuilder builder = factory.newDocumentBuilder();
Document doc = builder.parse(file);
//Transform the XML file into XSL
TransformDOM tfd = new TransformDOM();
tfd.TransformXMLToXsl(doc);
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
Step 6: Build and Run ứng dụng
Bài 3.2
Sử dụng biểu thức XPath in ra tất cả giá trị node firstname có trong file
Employees.xml
Step 1: Tạo lớp XpathExpressions.java để in ra tất cả giá trị node firstname
XpathExpressions.java
package estlexample;
Trang 7IT Research Department @BKAP 2015 Trang 7 / 15
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathFactory;
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
/**
*
* @author DELL
*/
publicclass XPathExpressions {
publicstaticvoid ExpressionFirstName(Document doc) {
try {
//Create XPath Factory
XPathFactory xpathfac = XPathFactory.newInstance();
//Create XPath
XPath xPath = xpathfac.newXPath();
//Create expression
String expression = "/employees/employee/firstname";
//print expression
System.out.println(expression);
//get node list form Employees.xml and expression
NodeList nodeList
= (NodeList) xPath.compile(expression).evaluate(doc,
XPathConstants.NODESET);
for (int i = 0; i < nodeList.getLength(); i++) {
//print node fristname
System.out.println(nodeList.item(i)
getFirstChild().getNodeValue());
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
Cấu trúc project sau khi hoàn thành
Trang 8Step 2: Triển khai hàm main của ứng dụng
ESTLExample.java
package estlexample;
import java.io.File;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
/**
*
* @author DELL
*/
publicclass ESTLExample {
/**
* @param args the command line arguments
*/
publicstaticvoid main(String[] args) {
try {
File file = new File("Employees.xml");
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setNamespaceAware(true);
DocumentBuilder builder = factory.newDocumentBuilder();
Document doc = builder.parse(file);
//Transform the XML file into XSL
// TransformDOM tfd = new TransformDOM();
// tfd.TransformXMLToXsl(doc);
XPathExpressions xpath = new XPathExpressions();
xpath.ExpressionFirstName(doc);
} catch (Exception ex) {
ex.printStackTrace();
Trang 9IT Research Department @BKAP 2015 Trang 9 / 15
}
}
}
Step 3: Build and Run ứng dụng
Bài 3.3
Sử dụng XPath Expression lấy dữ liệu từ file Employees.xml
In tất cả giá trị các node với điều kiện giá trị attribute của element employee có id =”112”
In giá trị các node của element employee có giá trị node location =
“Kansas”
Step 1: Tạo method ExpressionEmployeeAttribute – in tất cả các node
có giá trị attribute của element employee có id = “112” và
ExpressionNodeValue – in giá trị các node của element employee có giá trị node location = “Kansas” trong XpathExpression.java
XpathExpresion.java
…
publicstaticvoid ExpressionEmployeeAttribute(Document doc) {
try {
//Create XPath Factory
XPathFactory xpathfac = XPathFactory.newInstance();
//Create XPath
XPath xPath = xpathfac.newXPath();
Trang 10//Create expression
String expression = "/employees/employee[@id='112']";
//print expression
System.out.println(expression);
//Get node employee from Employees.xml and expression
Node node = (Node) xPath.compile(expression).evaluate(doc,
XPathConstants.NODE);
if (null != node) {
NodeList nodeList = node.getChildNodes();
for (int i = 0; null != nodeList && i < nodeList.getLength(); i++) {
//get all child node of node employee
Node nod = nodeList.item(i);
//print node
if (nod.getNodeType() == Node.ELEMENT_NODE) {
System.out.println(nodeList.item(i).getNodeName() + " : " +
nod.getFirstChild().getNodeValue());
}
}
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
publicstaticvoid ExpressionNodeValue(Document doc) {
try {
//Create XPath Factory
XPathFactory xpathfac = XPathFactory.newInstance();
//Create XPath
XPath xPath = xpathfac.newXPath();
//Create expression
String expression = "/employees/employee[location='Kansas']";
//print expression
System.out.println(expression);
//Get node employee from Employees.xml and expression
Node node = (Node) xPath.compile(expression).evaluate(doc,
XPathConstants.NODE);
if (null != node) {
//get all child node of node employee
NodeList nodeList = node.getChildNodes();
for (int i = 0; null != nodeList && i < nodeList.getLength(); i++) {
Trang 11IT Research Department @BKAP 2015 Trang 11 / 15
//print node
Node nod = nodeList.item(i);
if (nod.getNodeType() == Node.ELEMENT_NODE) {
System.out.println(nodeList.item(i).getNodeName() + " : " +
nod.getFirstChild().getNodeValue());
}
}
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
Step 2: Triển khai hàm main của ứng dụng
package estlexample;
import java.io.File;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
/**
*
* @author DELL
*/
publicclass ESTLExample {
/**
* @param args the command line arguments
*/
publicstaticvoid main(String[] args) {
try {
File file = new File("Employees.xml");
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setNamespaceAware(true);
DocumentBuilder builder = factory.newDocumentBuilder();
Document doc = builder.parse(file);
//Transform the XML file into XSL
// TransformDOM tfd = new TransformDOM();
// tfd.TransformXMLToXsl(doc);
Trang 12XPathExpressions xpath = new XPathExpressions();
// xpath.ExpressionFirstName(doc);
xpath.ExpressionEmployeeAttribute(doc);
xpath.ExpressionNodeValue(doc);
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
Step 3: Build and Run ứng dụng
Bài 3.4
Chỉnh employee có attribute giá trị id = “112” có node location có giá trị là
“Kansas”
Trang 13IT Research Department @BKAP 2015 Trang 13 / 15
In ra màn hình giá trị node firstname của các node có giá trị node location là
Kansas
In ra màn hình tổng số node có giá trị node location là Kansas
Nếu tổng số node có giá trị node location là Kansas nhiều hơn 1 thì in ra
màn hình “There are more than one employee located at Kansas”
Step 1: Tạo method XPathUsingJAXPAPI trong lớp XpathExpression để in ra màn hình giá trị node firstname, tổng số node, kiểm tra tổng số node có lớn hơn 1 không của các node có giá trị node location là Kansas
XpathExpression.java
…
publicstaticvoid XPathUsingJAXPAPI(Document doc) {
try {
//Create an XPathFactory
XPathFactory xFactory = XPathFactory.newInstance();
//Create an XPath object
XPath xpath = xFactory.newXPath();
//Compile the XPath expression
XPathExpression expr =
xpath.compile("/employees/employee[location='Kansas']/firstname/text()"); //Run the query and get a nodeset
Object result = expr.evaluate(doc, XPathConstants.NODESET);
//Cast the result to a DOM
NodeList nodes = (NodeList) result;
for (int i = 0; i < nodes.getLength(); i++) {
System.out.println(nodes.item(i).getNodeValue());
}
/* XPath expression to get the number of peoplelocated at Kansas */
expr = xpath.compile("count(/employees/employee[location='Kansas'])"); /* Run the query and get the number of nodes*/
Double number = (Double) expr.evaluate(doc, XPathConstants.NUMBER); System.out.println("Number of objects " + number);
/* Check more than one employeelocated at Kansas*/
expr = xpath.compile("count(/employees/employee[location='Kansas'])
>1");
/* Run the query and get the number of nodes*/
Trang 14Boolean check = (Boolean) expr.evaluate(doc, XPathConstants.BOOLEAN);
if (check == true) {
System.out.println("There are more than one employee located at
Kansas");
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
Step 2: Triển khai hàm main của ứng dụng
package estlexample;
import java.io.File;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
/**
*
* @author DELL
*/
publicclass ESTLExample {
/**
* @param args the command line arguments
*/
publicstaticvoid main(String[] args) {
try {
File file = new File("Employees.xml");
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setNamespaceAware(true);
DocumentBuilder builder = factory.newDocumentBuilder();
Document doc = builder.parse(file);
//Transform the XML file into XSL
// TransformDOM tfd = new TransformDOM();
// tfd.TransformXMLToXsl(doc);
XPathExpressions xpath = new XPathExpressions();
// xpath.ExpressionFirstName(doc);
// xpath.ExpressionEmployeeAttribute(doc);
// xpath.ExpressionNodeValue(doc);
Trang 15IT Research Department @BKAP 2015 Trang 15 / 15
xpath.XPathUsingJAXPAPI(doc);
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
Step 3: Build and Run ứng dụng
Phần II Bài tập tự làm