You are on page 1of 43

Lp trnh XML vi Java

Trnh by: Ng B Nam Phng

Ni dung trnh by

Xml Parsers c ni dung ti liu XML To ti liu XML XSLT

XML Parser
Java h tr 2 loi xml parser: Tree Parser - DOM Parser: phn tch ni dung ti liu XML theo m hnh cy phn cp Streaming Parser - SAX Parser ( Simple API for XML ), StAX Parser: pht sinh cc s kin trong qu trnh duyt ti liu Xml

DOM Parser
V d:
<font> <name>Helvetica</name> <size>36</size> </font> Node font c 5 node con: whitespace name whitespace size whitespace

DOM Parser

SAX Parser
Ph hp i vi cc ti liu c kch thc ln v ni dung x l tng i n gin. Pht sinh cc s kin tng ng trong qu trnh c ti liu. Application s to cc event listener lng nghe cc event do parser pht ra truy xut ni dung ti liu. DOM Parser c xy dng bn trn SAX Parser. DOM Parser xy dng cy ti liu DOM tree da trn cc event n nhn c do SAX Parser tr v.

StAX Parser (Streaming API for XML )


Cung cp m hnh x l c ti liu XML n gin v thun tin hn SAX parser Application s gi cc hm ca parser v cc s kin cn quan tm truy xut ni dung ti liu

Ni dung trnh by

Xml Parsers c ni dung ti liu XML To ti liu XML XSLT

c ti liu XML DOM Parser XPath Expression StAX Parser

DOM Parser
import javax.xml.parsers.*; import org.w3c.dom.*; DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); Document doc = builder.parse(new File("Sach.xml"));

DOM Parser
// truy cp node gc ca ti liu Element root = doc.getDocumentElement(); // ly v danh sch node con ca mt node NodeList list = root.getChildNodes(); for(int i=0;i<list.getLength();++i) { // x l tng node Node node = list.item(i); }

DOM Parser
// X l cc node con dng Element
NodeList list = root.getChildNodes(); for(int i=0;i<list.getLength();++i) { Node node = list.item(i); if(node instanceof Element) { // x l node name v size Element element = (Element) node; } }

DOM Parser
Rt trch ni dung trong node name v size: Element element = (Element)node; // ang truy cp ti node name v size Text textNode = (Text)element.getFirstChild(); String content = textNode.getData(); if(element.getTagName().equals(name)) name = content; else if(element.getTagName().equals(size)) size = Integer.parseInt(content);

DOM Parser
Cch khc duyt v x l trn danh sch cc node con ca 1 node for(Node childNode = element.getFirstChild(); childNode != null; childNode = childNode.getNextSibling() ) { }

DOM Parser
Ly danh sch attributes ca 1 node:
getAttributes : tr v NamedNodeMap i din cho danh sch cc attribute ca node

NamedNodeMap attributes = element.getAttributes(); for(int i=0;i<attributes.getLength();++i) { Node attributeNode = attributes.item(i); String name = attributeNode.getNodeName(); String value = attributeNode.getNodeValue(); }

DOM Parser
Ly gi tr thuc tnh thng qua tn thuc tnh V d:
<Sach MaSach=1 TenSach=VB.NET />
String maSach = element.getAttribute(MaSach); String tenSach = element.getAttribute(TenSach);

c ti liu XML DOM Parser XPath Expression StAX Parser

XPath
L cc biu thc ng dn cho php truy cp n cc node trong cy ti liu d dng m khng cn phi duyt v tm kim trn ton b cy ti liu. Khi to i tng XPath: import javax.xml.xpath.*; XPathFactory xpFactory = XPathFactory.newInstance(); XPath path = xpFactory.newXPath();

XPath

Ly gi tr ca 1 element hoc 1 attribute trong ti liu:


V d: <EbookList> <Ebook> <ID>123</ID> <Title>C#</Title> </Ebook> <Ebook ID=234 Title=Vb.net /> </EbookList>

int id = Integer.parseInt(path.evaluate(/EbookList/Ebook[1]/ID,doc)); String title = path.evaluate(/EbookList/Ebook[1]/Title,doc); id = Integer.parseInt(path.evaluate(/EbookList/Ebook[2]/@ID,doc)); title = path.evaluate(/EbookList/Ebook[2]/@Title,doc);

XPath
Ly v danh sch cc Node
NodeList list = (NodeList)path.evaluate(/EbookList/Ebook, doc, XPathContants.NODESET);

Ly v 1 node
Node node = (Node)path.evaluate(/EbookList/Ebook[1], doc, XPathContants.NODE);

Ly v kt qu l gi tr ca mt hm
int count = ((Number)path.evaluate("count(/EbookList/Ebook)", doc,XPathConstants.NUMBER)).intValue();

c ti liu XML DOM Parser XPath Expression StAX Parser

StAX Parser - Events


<font> <name> Helvetica </name> <size units="pt"> 36 </size> </font>
START_ELEMENT, element name: font CHARACTERS, content: white space START_ELEMENT, element name: name CHARACTERS, content: Helvetica END_ELEMENT, element name: name CHARACTERS, content: white space START_ELEMENT, element name: size CHARACTERS, content: 36 END_ELEMENT, element name: size CHARACTERS, content: white space END_ELEMENT, element name: font

StAX Parser
// M ti liu xml import javax.xml.stream.*; XMLInputFactory factory = XMLInputFactory.newInstance(); XMLStreamReader parser = factory.createXMLStreamReader(new FileReader("DBSach.xml"));

StAX Parser
while(parser.hasNext()) { // c v x l ni dung ti liu XML int event = parser.next(); if(event == XMLStreamConstants.START_ELEMENT) { if(parser.getLocalName().equals("Sach")==true) { sach = new Sach(); } else if(parser.getLocalName().equals("MaSach")==true) { sach.setMaSach(Integer.parseInt(parser.getElementText())); } else if(parser.getLocalName().equals("TenSach")==true) { sach.setTenSach(parser.getElementText()); listSach.add(sach); } } }

StAX Parser
Ly gi tr thuc tnh bn trong Element:
<Sach SoTrang="102" ISBN="104"> String soTrang = parser.getAttributeValue(null, "SoTrang"); String ISBN = parser.getAttributeValue(null,"ISBN");

Ni dung trnh by

Xml Parsers c ni dung ti liu XML To ti liu XML XSLT

To tp tin XML DOM Parser


To ni dung ti liu XML: createElement( nodeName ); createTextNode( textContent ); appendChild( nodeName ); setAttribute( attributeName , value );

To tp tin XML - DOM


V d: Element root = doc.createElement(root); Element child1 = doc.createElement(child); child1.setAttribute(at1,value1); Text textNode1 = doc.createTextNode(text content);

doc.appendChild(root); root.appendChild(child); child.appendChild(textNode1);

To tp tin XML - DOM


XML DOM API hin thi khng h tr vic kt xut ni dung cy ti liu ln b nh ph. Ta c th s dng XSLT thc hin: import javax.xml.transform.*;

Transformer t = TransformerFactory.newInstance().newTransformer() t.setOutputProperty (OutputKeys.INDENT, "yes"); t.setOutputProperty (OutputKeys.METHOD, "xml"); t.setOutputProperty ("{http://xml.apache.org/xslt}indent-amount", "2"); t.transform(new DOMSource(doc), new StreamResult(new FileOutputStream("temp.xml")));

To tp tin Xml - StAX


S dng i tng XMLStreamWriter cc phng thc: writeStartDocument() writeEndDocument() writeStartElement(elementName) writeEndElement() writeAttribute(attributeName,attributeValue) writeCharacters(text)

To tp tin Xml - StAX


To i tng XMLStreamWriter File file = new File("StAXOutput.xml"); XMLOutputFactory factory = XMLOutputFactory.newInstance(); XMLStreamWriter writer = factory.createXMLStreamWriter(new FileOutputStream(file),"UTF-8");

To tp tin Xml - StAX


V d: <Sach MaSach=123> <TenSach> harry potter </TenSach> <GiaTien> 123000 </GiaTien> </Sach>

writer.writeStartDocument(); writer. writeStartElement (Sach); writer. writeAttribute (MaSach,123); writer. writeStartElement (TenSach); writer. writeCharacters (harry potter) writer. writeEndElement (); writer. writeStartElement (GiaTien); writer. writeCharacters (123000); writer. writeEndElement (); writer. writeEndElement (); writer. writeEndDocument ();

Ni dung trnh by

Xml Parsers c ni dung ti liu XML To ti liu XML XSLT

XSLT XSL Transformation


L ngn ng c t cc lut chuyn i ti liu XML sang format khc ( plain text, XML, HTML, .. )

XSLT XSL Transformation

<?xml version="1.0" encoding=utf-8"?> <xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0"> <xsl:output method="html"/>


template1

template2 ... </xsl:stylesheet>

XSLT XSL Transformation


<xsl:template>: dng nh ngha cc template

<xsl:stylesheet version = '1.0 xmlns:xsl='http://www.w3.org/1999/XSL/Transform'>


<xsl:template match="> <h1> <xsl:value-of select="//element1 /> </h1> <h2> <xsl:value-of select="//element2 /> </h2> </xsl:template> <xsl:template match="> Biu thc XPATH .. </xsl:template> </xsl:stylesheet>
Khi gp nhng th tha k th thc hin nhng ch th sau

XSLT XSL Transformation


<xsl:value-of> Rt trch ni dung nm trong cc th XML (
inner text hay thuc tnh ca node ) v kt xut ra file kt qu Ni dung rt trch c xc nh thng qua thuc tnh select Nu select tr v mt tp cc th th ni dung tt c cc th ny u c kt xut ra file kt qu
<hocsinh> <hoten>Nguyen Van A</hoten> <mssv>0412341</mssv> </hocsinh>

<xsl:stylesheet.> <xsl:template match=/> <h1><xsl:value-of select=//hoten/></h1> <h2><xsl:value-of select=//mssv/></h2> </xsl:template> </xsl:stylesheet>

XSLT XSL Transformation


<xsl:apply-templates >
<source> <a1>a1</a1> <a2>a2</a2> </source> -Khng c template -Khng c template Mc nh: tr ra ni dung ca tha1 a2 p dng x l mc nh: tip tc so khp cho tt c th con ca th hin hnh

<xsl:stylesheet>
<xsl:template match=/> <xsl:apply-templates/> </xsl:template>

</xsl:stylesheet>

XSLT XSL Transformation


<?xml version="1.0" encoding="UTF-8"?> <staff> <employee> <name>Carl Cracker</name> <salary>75000</salary> <hiredate year="1987" month="12" day="15"/> </employee> <employee> <name>Harry Hacker</name> <salary>50000</salary> <hiredate year="1989" month="10" day="1"/> </employee> <employee> <name>Tony Tester</name> <salary>40000</salary> <hiredate year="1990" month="3" day="15"/> </employee> </staff>

XSLT XSL Transformation


<xsl:output method="xml" indent="yes"/> .. <xsl:template match="/"> <table border="1" > <tr> <td>H tn</td> <td>Lng</td> <td>Ngy sinh</td> </tr> <xsl:apply-templates select="/staff/employee" /> </table> </xsl:template>

XSLT XSL Transformation


<xsl:template match="employee"> <tr> <Td> <xsl:value-of select="name" /> </Td> <td> <xsl:value-of select="salary" /> </td> <td> <xsl:value-of select="hiredate/@day" /> <xsl:value-of select="hiredate/@month" /> <xsl:value-of select="hiredate/@year" /> </td> </tr> </xsl:template>

XSLT XSL Transformation


File styleSheet = new File("transform.xsl");
StreamSource styleSource = new StreamSource(styleSheet); TransformerFactory factory = TransformerFactory.newInstance(); Transformer t = factory.newTransformer(styleSource); File file = new File("input.xml");

t.transform(new StreamSource(file), new


StreamResult(output.html"));

Cm n Hi p

You might also like