0
Java XML Programming Svetlin Nakov Bulgarian Association of Software Developers www.devbg.org
Contents <ul><li>Introduction to XML Parsers </li></ul><ul><ul><li>The DOM Parser </li></ul></ul><ul><ul><li>The SAX Parse...
XML Parsers
XML Parsers <ul><li>XML parsers are programming libraries that make the work with   XML easier </li></ul><ul><li>They are ...
XML Parsers – Models <ul><li>DOM (Document Object Model) </li></ul><ul><ul><li>Represents   XML documents as a tree  in th...
Using a XML Parser <ul><li>Three basic steps to using an XML parser </li></ul><ul><ul><li>Create a parser object  </li></u...
Types of Parser <ul><li>There are several different ways to categorize parsers: </li></ul><ul><ul><li>Validating versus no...
The DOM Parser
DOM Parser Architecture
DOM Key Features <ul><li>The DOM API is generally an easier API to use </li></ul><ul><ul><li>It provides a familiar tree s...
The DOM   Parser – Example  <ul><li>The   following XML document is given : </li></ul><?xml version=&quot;1.0&quot;?> <lib...
The DOM   Parser – Example <ul><li>This document is represented in the in the memory as a DOM tree in the following way: <...
The SAX Parser
SAX Key Features <ul><li>The Simple API for XML (SAX) </li></ul><ul><ul><li>Event-driven </li></ul></ul><ul><ul><li>S eria...
The SAX Parser <ul><li>Working with SAX is much complex </li></ul><ul><li>Old technology </li></ul><ul><li>Use it's new eq...
The StAX Parser <ul><li>Like SAX but </li></ul><ul><ul><li>Not event driven (not callback based) </li></ul></ul><ul><ul><l...
When to Use   DOM   and When to Use SAX/StAX? <ul><li>The DOM processing model is suitable when: </li></ul><ul><ul><li>Pro...
<ul><li>The SAX/StAX   processing model is suitable when : </li></ul><ul><ul><li>Processing big documents </li></ul></ul><...
Introduction to  JAXP
JAXP <ul><li>J ava  A PI for  X ML  P rocessing  </li></ul><ul><li>Designed to be flexible </li></ul><ul><li>F acilitate t...
JAXP – Plugability <ul><li>JAXP allows you to use any XML-compliant parser </li></ul><ul><li>R egardless of which vendor's...
JAXP – Independence <ul><li>To achieve the goal of XML processor independence </li></ul><ul><ul><li>A pplication should li...
JAXP Packages <ul><li>j avax.xml.parsers </li></ul><ul><ul><li>The JAXP APIs </li></ul></ul><ul><ul><li>P rovide s  a comm...
JAXP Packages (2) <ul><li>org.xml.sax   </li></ul><ul><ul><li>Defines the basic SAX APIs </li></ul></ul><ul><li>javax.xml....
Using the DOM Parser
DOM  Document  Structure Document +--- Element <dots> +--- Text &quot;this is before the first dot |   and it continues on...
DOM  Document  Structure <ul><li>There’s a text node between every  pair of element nodes, even if the  text is empty </li...
DOM Classes Hierarchy
Using DOM import javax.xml.parsers.*; import org.w3c.dom.*; //  G et a DocumentBuilder object DocumentBuilderFactory dbf =...
DOM  Document  Access Idioms // get the root of the Document tree Element root = doc.getDocumentElement(); // get nodes in...
More  Document  Accessors Node   access methods: String getNodeName () short getNodeType () Document getOwnerDocument () b...
More  Document  Accessors Element   extends   Node   and adds these access methods: String getTagName () boolean hasAttrib...
Writing a  Document  as XML <ul><li>JAXP do not specify how to write XML document to a file </li></ul><ul><li>Most JAXP im...
Reading and Parsing XML Documents with the DOM Parser Live Demo
Creating & Manipulating DOM Documents // Get new empty Document from DocumentBuilder Document doc = docBuilder.newDocument...
More  Document  Manipulators Node   manipulation methods: void setNodeValue ( String   nodeValue ) Node appendChild ( Node...
Building Documents with the DOM Parser Live Demo
Using The StAX Parser
The StAX Parser in Java <ul><li>As from Java 6 the StAX parser is available as part of Java </li></ul><ul><li>Two basic St...
Parsing Documents with the StAX Parser – Example FileReader fileReader = new FileReader(&quot;Student.xml&quot;); XMLInput...
Parsing Documents with the StAX Parser Live Demo
Creating Documents with the StAX Parser – Example String fileName = &quot;Customers.xml&quot;; FileWriter fileWriter = new...
Parsing Documents with the StAX Parser Live Demo
Using XPath in Java Searching nodes in XML documents
Parsing XML Documents with XPath <ul><li>To evaluate an XPath expression in Java, create an XPath object </li></ul><ul><li...
Sample XML Document <ul><li><?xml version=&quot;1.0&quot; encoding=&quot;windows-1251&quot;?> </li></ul><ul><li><items cul...
Parsing with XPath – Example <ul><li>For example, obtains as result the string &quot; 0.48 “ </li></ul><ul><li>XPath can a...
Using XPath Live Demo
Modifying XML with DOM and XPath Live Demo
XSL Transformations in JAXP javax.xml.transform.Transformer
XSLT API
Transforming with XSLT in Java with JAXP <ul><li>The JAXP uses a factory design pattern </li></ul><ul><ul><li>This hides t...
Transforming with XSLT in Java with JAXP (2) <ul><li>Establish the factory  and  environment </li></ul><ul><li>Load and co...
Transforming with XSL – Example <?xml version=&quot;1.0&quot;?> <library name=&quot;.NET Developer's Library&quot;> <book>...
Transforming with XSL – Example (2) <?xml version=&quot;1.0&quot; encoding=&quot;windows-1251&quot;?> <xsl:stylesheet vers...
Transforming with XSL – Example (3) <tr bgcolor=&quot;#EEEEEE&quot;> <td><b>Заглавие</b></td> <td><b>Автор</b></td> </tr> ...
Transforming with XSL – Example (4) public class XSLTransformDemo { public static void main(String[] args)  throws Transfo...
Transforming with XSL – Example (5) <html> <head> <meta http-equiv=&quot;Content-Type&quot; content=&quot;text/html; chars...
Transforming with XSL – Example (6) <tr bgcolor=&quot;white&quot;> <td>Programming Microsoft .NET</td> <td>Jeff Prosise</t...
XSL Transformations Live Demo
Exercises <ul><li>Write a program that extracts from the file &quot; students.xml &quot; all available information about t...
Exercises (2) <ul><li>Write a program that extracts from the file &quot; students.xml &quot; all available information abo...
Exercises (3) <ul><li>Using the StAX parser write a program that extracts all books' names from the file  catalog .xml . <...
Exercises (4) <ul><li>Write a JAXP based Java program to apply the XSL stylesheet over the XML document. </li></ul><ul><li...
Exercises (5) <ul><li>Write a XSL stylesheet for transforming the CV to HTML and XML with other structure. Write a program...
Upcoming SlideShare
Loading in...5
×

Processing XML with Java

3,425

Published on

Processing XML with Java and JAXP - http://javaeecourse.devg.org

Published in: Education
1 Comment
1 Like
Statistics
Notes
  • Good information on processing XML with Java
       Reply 
    Are you sure you want to  Yes  No
    Your message goes here
No Downloads
Views
Total Views
3,425
On Slideshare
0
From Embeds
0
Number of Embeds
2
Actions
Shares
0
Downloads
174
Comments
1
Likes
1
Embeds 0
No embeds

No notes for slide
  • (c) 2007 National Academy for Software Development - http://academy.devbg.org All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.* ##
  • (c) 2007 National Academy for Software Development - http://academy.devbg.org All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.* ##
  • (c) 2007 National Academy for Software Development - http://academy.devbg.org All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.* ##
  • (c) 2007 National Academy for Software Development - http://academy.devbg.org All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.* ##
  • (c) 2007 National Academy for Software Development - http://academy.devbg.org All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.* ##
  • (c) 2007 National Academy for Software Development - http://academy.devbg.org All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.* ##
  • (c) 2007 National Academy for Software Development - http://academy.devbg.org All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.* ##
  • (c) 2007 National Academy for Software Development - http://academy.devbg.org All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.* ##
  • (c) 2007 National Academy for Software Development - http://academy.devbg.org All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.* ##
  • (c) 2007 National Academy for Software Development - http://academy.devbg.org All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.* ##
  • (c) 2007 National Academy for Software Development - http://academy.devbg.org All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.* ##
  • (c) 2007 National Academy for Software Development - http://academy.devbg.org All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.* ##
  • (c) 2007 National Academy for Software Development - http://academy.devbg.org All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.* ##
  • (c) 2007 National Academy for Software Development - http://academy.devbg.org All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.* ##
  • (c) 2007 National Academy for Software Development - http://academy.devbg.org All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.* ##
  • (c) 2007 National Academy for Software Development - http://academy.devbg.org All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.* ##
  • (c) 2007 National Academy for Software Development - http://academy.devbg.org All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.* ##
  • (c) 2007 National Academy for Software Development - http://academy.devbg.org All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.* ##
  • (c) 2007 National Academy for Software Development - http://academy.devbg.org All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.* ##
  • (c) 2007 National Academy for Software Development - http://academy.devbg.org All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.* ##
  • (c) 2007 National Academy for Software Development - http://academy.devbg.org All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.* ##
  • (c) 2007 National Academy for Software Development - http://academy.devbg.org All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.* ##
  • (c) 2007 National Academy for Software Development - http://academy.devbg.org All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.* ##
  • (c) 2007 National Academy for Software Development - http://academy.devbg.org All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.* ##
  • (c) 2007 National Academy for Software Development - http://academy.devbg.org All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.* ##
  • (c) 2007 National Academy for Software Development - http://academy.devbg.org All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.* ##
  • (c) 2007 National Academy for Software Development - http://academy.devbg.org All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.* ##
  • (c) 2007 National Academy for Software Development - http://academy.devbg.org All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.* ##
  • (c) 2007 National Academy for Software Development - http://academy.devbg.org All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.* ##
  • (c) 2007 National Academy for Software Development - http://academy.devbg.org All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.* ##
  • (c) 2007 National Academy for Software Development - http://academy.devbg.org All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.* ## Any changes made since the last commit will be ignored – usually rollback is used in combination with Java’s exception handling ability to recover from unpredictable errors.
  • (c) 2007 National Academy for Software Development - http://academy.devbg.org All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.* ##
  • (c) 2007 National Academy for Software Development - http://academy.devbg.org All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.* ##
  • (c) 2007 National Academy for Software Development - http://academy.devbg.org All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.* ##
  • (c) 2007 National Academy for Software Development - http://academy.devbg.org All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.* ##
  • (c) 2007 National Academy for Software Development - http://academy.devbg.org All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.* ##
  • (c) 2007 National Academy for Software Development - http://academy.devbg.org All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.* ##
  • (c) 2007 National Academy for Software Development - http://academy.devbg.org All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.* ##
  • Transcript of "Processing XML with Java"

    1. 1. Java XML Programming Svetlin Nakov Bulgarian Association of Software Developers www.devbg.org
    2. 2. Contents <ul><li>Introduction to XML Parsers </li></ul><ul><ul><li>The DOM Parser </li></ul></ul><ul><ul><li>The SAX Parser </li></ul></ul><ul><ul><li>The StAX Parser </li></ul></ul><ul><li>Introduction to JAXP </li></ul><ul><ul><li>Using DOM </li></ul></ul><ul><ul><li>Using StAX </li></ul></ul><ul><ul><li>Java API for XPath </li></ul></ul><ul><ul><li>Java API for XSLT </li></ul></ul>
    3. 3. XML Parsers
    4. 4. XML Parsers <ul><li>XML parsers are programming libraries that make the work with XML easier </li></ul><ul><li>They are used for: </li></ul><ul><ul><li>Extracting data from XML documents </li></ul></ul><ul><ul><li>Building XML documents </li></ul></ul><ul><ul><li>Validating XML documents by given scheme </li></ul></ul>
    5. 5. XML Parsers – Models <ul><li>DOM (Document Object Model) </li></ul><ul><ul><li>Represents XML documents as a tree in the memory </li></ul></ul><ul><ul><li>Allows flexible and easy processing </li></ul></ul><ul><ul><li>Supports changing the document </li></ul></ul><ul><li>SAX (Simple API for XML Processing) </li></ul><ul><ul><li>Reads XML documents consequently (like a stream) </li></ul></ul><ul><ul><li>Allows read-only / write-only access </li></ul></ul><ul><li>StAX (Streaming API for XML) </li></ul><ul><ul><li>Similar to SAX but simplified </li></ul></ul>
    6. 6. Using a XML Parser <ul><li>Three basic steps to using an XML parser </li></ul><ul><ul><li>Create a parser object </li></ul></ul><ul><ul><li>Pass your XML document to the parser </li></ul></ul><ul><ul><li>Process the results </li></ul></ul><ul><li>Generally, writing out XML is outside scope of parsers </li></ul><ul><ul><li>Some parsers may implement such mechanisms </li></ul></ul>
    7. 7. Types of Parser <ul><li>There are several different ways to categorize parsers: </li></ul><ul><ul><li>Validating versus non-validating parsers </li></ul></ul><ul><ul><li>Parsers that support the Document Object Model (DOM) </li></ul></ul><ul><ul><li>Parsers that support the Simple API for XML (SAX) </li></ul></ul><ul><ul><li>Streaming parsers (StAX) </li></ul></ul><ul><ul><li>Parsers written in a particular language (Java, C#, C++, Perl, etc.) </li></ul></ul>
    8. 8. The DOM Parser
    9. 9. DOM Parser Architecture
    10. 10. DOM Key Features <ul><li>The DOM API is generally an easier API to use </li></ul><ul><ul><li>It provides a familiar tree structure of objects </li></ul></ul><ul><ul><li>You can use it to manipulate the hierarchy of a XML document </li></ul></ul><ul><li>The DOM API is ideal for interactive applications </li></ul><ul><ul><li>The entire object model is present in memory </li></ul></ul>
    11. 11. The DOM Parser – Example <ul><li>The following XML document is given : </li></ul><?xml version=&quot;1.0&quot;?> <library name=&quot;.NET Developer's Library&quot;> <book> <title>Programming Microsoft .NET</title> <author>Jeff Prosise</author> <isbn>0-7356-1376-1</isbn> </book> <book> <title>Microsoft .NET for Programmers</title> <author>Fergal Grimes</author> <isbn>1-930110-19-7</isbn > </book> </library>
    12. 12. The DOM Parser – Example <ul><li>This document is represented in the in the memory as a DOM tree in the following way: </li></ul>Header part Root node
    13. 13. The SAX Parser
    14. 14. SAX Key Features <ul><li>The Simple API for XML (SAX) </li></ul><ul><ul><li>Event-driven </li></ul></ul><ul><ul><li>S erial-access mechanism </li></ul></ul><ul><ul><li>E lement-by-element processing </li></ul></ul><ul><ul><li>Do not allow going backwards or jumping ahead </li></ul></ul><ul><ul><li>Require many times less resources </li></ul></ul><ul><ul><ul><li>Memory </li></ul></ul></ul><ul><ul><ul><li>CPU time </li></ul></ul></ul><ul><ul><li>Work over streams </li></ul></ul>
    15. 15. The SAX Parser <ul><li>Working with SAX is much complex </li></ul><ul><li>Old technology </li></ul><ul><li>Use it's new equivalent – the StAX parser </li></ul>
    16. 16. The StAX Parser <ul><li>Like SAX but </li></ul><ul><ul><li>Not event driven (not callback based) </li></ul></ul><ul><ul><li>&quot;Pull&quot;-based </li></ul></ul><ul><ul><li>Developer manually say &quot;go to next element&quot; and analyze it </li></ul></ul><ul><li>It's a new feature in Java 6.0! </li></ul>
    17. 17. When to Use DOM and When to Use SAX/StAX? <ul><li>The DOM processing model is suitable when: </li></ul><ul><ul><li>Processing small documents </li></ul></ul><ul><ul><li>There is a need of flexibility </li></ul></ul><ul><ul><li>There is a need of direct access to different nodes of the document </li></ul></ul><ul><ul><li>We need to change the document </li></ul></ul>
    18. 18. <ul><li>The SAX/StAX processing model is suitable when : </li></ul><ul><ul><li>Processing big documents </li></ul></ul><ul><ul><ul><li>Big XML documents (e.g. > 20-30 MB) cannot be processed with DOM! </li></ul></ul></ul><ul><ul><li>The performance is important </li></ul></ul><ul><ul><li>There is no need to change the document nodes </li></ul></ul><ul><ul><li>SAX/StAX is read-only / write-only (like the streams) </li></ul></ul>When to Use DOM and When to Use SAX/StAX?
    19. 19. Introduction to JAXP
    20. 20. JAXP <ul><li>J ava A PI for X ML P rocessing </li></ul><ul><li>Designed to be flexible </li></ul><ul><li>F acilitate the use of XML on the Java platform </li></ul><ul><li>P rovides a common interface for these standard APIs </li></ul><ul><ul><li>DOM </li></ul></ul><ul><ul><li>SAX, StAX </li></ul></ul><ul><ul><li>XPath and XSL Transformations (XSLT) </li></ul></ul>
    21. 21. JAXP – Plugability <ul><li>JAXP allows you to use any XML-compliant parser </li></ul><ul><li>R egardless of which vendor's implementation is actually being used </li></ul><ul><li>P luggability layer </li></ul><ul><ul><li>L ets you plug in an implementation of the SAX or DOM API </li></ul></ul><ul><ul><li>L et s you control how your XML data is displayed </li></ul></ul>
    22. 22. JAXP – Independence <ul><li>To achieve the goal of XML processor independence </li></ul><ul><ul><li>A pplication should limit itself to the JAXP API </li></ul></ul><ul><ul><li>A void using implementation-dependent APIs and behavior </li></ul></ul>
    23. 23. JAXP Packages <ul><li>j avax.xml.parsers </li></ul><ul><ul><li>The JAXP APIs </li></ul></ul><ul><ul><li>P rovide s a common interface for different vendors ' SAX and DOM parsers </li></ul></ul><ul><li>org.w3c.dom </li></ul><ul><ul><li>Defines the DOM classes </li></ul></ul><ul><ul><li>Document class and all the components of a DOM </li></ul></ul>
    24. 24. JAXP Packages (2) <ul><li>org.xml.sax </li></ul><ul><ul><li>Defines the basic SAX APIs </li></ul></ul><ul><li>javax.xml.stream </li></ul><ul><ul><li>Define the basic StAX classes </li></ul></ul><ul><li>javax.xml.xpath </li></ul><ul><ul><li>Defines API for the evaluation of XPath expressions </li></ul></ul><ul><li>javax.xml.transform </li></ul><ul><ul><li>Defines the XSLT APIs that let you transform XML into other forms </li></ul></ul>
    25. 25. Using the DOM Parser
    26. 26. DOM Document Structure Document +--- Element <dots> +--- Text &quot;this is before the first dot | and it continues on multiple lines&quot; +--- Element <dot> +--- Text &quot;&quot; +--- Element <dot> +--- Text &quot;&quot; +--- Element <flip> | +--- Text &quot;flip is on&quot; | +--- Element <dot> | +--- Text &quot;&quot; | +--- Element <dot> | +--- Text &quot;&quot; +--- Text &quot;flip is off&quot; +--- Element <dot> +--- Text &quot;&quot; +--- Element <extra> | +--- Text &quot;stuff&quot; +--- Text &quot;&quot; +--- Comment &quot;a final comment&quot; +--- Text &quot;&quot; XML input: Document structure: <?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?> <dots> this is before the first dot and it continues on multiple lines <dot x=&quot;9&quot; y=&quot;81&quot; /> <dot x=&quot;11&quot; y=&quot;121&quot; /> <flip> flip is on <dot x=&quot;196&quot; y=&quot;14&quot; /> <dot x=&quot;169&quot; y=&quot;13&quot; /> </flip> flip is off <dot x=&quot;12&quot; y=&quot;144&quot; /> <extra>stuff</extra> <!-- a final comment --> </dots>
    27. 27. DOM Document Structure <ul><li>There’s a text node between every pair of element nodes, even if the text is empty </li></ul><ul><li>XML comments appear in special comment nodes </li></ul><ul><li>Element attributes do not appear in tree </li></ul><ul><ul><li>Available through Element object </li></ul></ul>
    28. 28. DOM Classes Hierarchy
    29. 29. Using DOM import javax.xml.parsers.*; import org.w3c.dom.*; // G et a DocumentBuilder object DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); DocumentBuilder db = null; try { db = dbf.newDocumentBuilder(); } catch (ParserConfigurationException e) { e.printStackTrace(); } // I nvoke parser to get a Document Document doc = db.parse(inputStream); Document doc = db.parse(file); Document doc = db.parse(url); Here’s the basic recipe for getting started:
    30. 30. DOM Document Access Idioms // get the root of the Document tree Element root = doc.getDocumentElement(); // get nodes in subtree by tag name NodeList dots = root.getElementsByTagName(&quot;dot&quot;); // get first dot element Element firstDot = (Element) dots.item(0); // get x attribute of first dot String x = firstDot.getAttribute(&quot;x&quot;); <ul><li>OK, say we have a Document . How do we get at the pieces of it? </li></ul><ul><li>Here are some common idioms: </li></ul>
    31. 31. More Document Accessors Node access methods: String getNodeName () short getNodeType () Document getOwnerDocument () boolean hasChildNodes () NodeList getChildNodes () Node getFirstChild () Node getLastChild () Node getParentNode () Node getNextSibling () Node getPreviousSibling () boolean hasAttributes () ... and more ... e.g. DOCUMENT_NODE, ELEMENT_NODE, TEXT_NODE, COMMENT_NODE, etc.
    32. 32. More Document Accessors Element extends Node and adds these access methods: String getTagName () boolean hasAttribute ( String name ) String getAttribute ( String name ) NodeList getElementsByTagName ( String name ) … and more … Document extends Node and adds these access methods: Element getDocumentElement () DocumentType getDoctype () ... plus the Element methods just mentioned ... ... and more ...
    33. 33. Writing a Document as XML <ul><li>JAXP do not specify how to write XML document to a file </li></ul><ul><li>Most JAXP implementations have own classes for writing XML files </li></ul><ul><ul><li>E.g. the class XMLSerializer in Apache Xerces (the standard parser in J2SE 5.0) </li></ul></ul>import com.sun.org.apache.xml.internal. serialize.XMLSerializer; XMLSerializer xmlser = new XMLSerializer(); xmlser.setOutputByteStream(System.out); xmlser.serialize(doc);
    34. 34. Reading and Parsing XML Documents with the DOM Parser Live Demo
    35. 35. Creating & Manipulating DOM Documents // Get new empty Document from DocumentBuilder Document doc = docBuilder.newDocument(); // Create a new <dots> element // and add it to the document as root Element root = doc.createElement(&quot;dots&quot;); doc.appendChild(root); // Create a new <dot> element // and add as child of the root Element dot = doc.createElement(&quot;dot&quot;); dot.setAttribute(&quot;x&quot;, &quot;9&quot;); dot.setAttribute(&quot;y&quot;, &quot;81&quot;); root.appendChild(dot); <ul><li>The DOM API also includes lots of methods for creating and manipulating Document objects: </li></ul>
    36. 36. More Document Manipulators Node manipulation methods: void setNodeValue ( String nodeValue ) Node appendChild ( Node newChild ) Node insertBefore ( Node newChild , Node refChild ) Node removeChild ( Node oldChild ) ... and more ... Element manipulation methods: void setAttribute ( String name , String value ) void removeAttribute ( String name ) … and more … Document manipulation methods: Text createTextNode ( String data ) Comment createCommentNode ( String data ) ... and more ...
    37. 37. Building Documents with the DOM Parser Live Demo
    38. 38. Using The StAX Parser
    39. 39. The StAX Parser in Java <ul><li>As from Java 6 the StAX parser is available as part of Java </li></ul><ul><li>Two basic StAX classes </li></ul><ul><ul><li>XMLStreamReader </li></ul></ul><ul><ul><ul><li>Pull based XML streaming API for parsing XML documents – read-only </li></ul></ul></ul><ul><ul><li>XMLStreamWriter </li></ul></ul><ul><ul><ul><li>Streaming based builder for XML documents – write-only </li></ul></ul></ul>
    40. 40. Parsing Documents with the StAX Parser – Example FileReader fileReader = new FileReader(&quot;Student.xml&quot;); XMLInputFactory factory = XMLInputFactory. newInstance (); XMLStreamReader reader = factory.createXMLStreamReader(fileReader); String element = &quot;&quot;; while (reader.hasNext()) { if (reader.isStartElement()) { element = reader.getLocalName(); } else if (reader.isCharacters() && !reader.isWhiteSpace()) { System. out .printf(&quot;%s - %s%n&quot;, element, reader.getText()); } reader.next(); } reader.close()
    41. 41. Parsing Documents with the StAX Parser Live Demo
    42. 42. Creating Documents with the StAX Parser – Example String fileName = &quot;Customers.xml&quot;; FileWriter fileWriter = new FileWriter(fileName); XMLOutputFactory factory = XMLOutputFactory. newInstance (); XMLStreamWriter writer = factory.createXMLStreamWriter(fileWriter); writer.writeStartDocument(); writer.writeStartElement(&quot;Customers&quot;); writer.writeStartElement(&quot;Customer&quot;); writer.writeStartElement(&quot;Name&quot;); writer.writeCharacters(&quot;ABC Pizza&quot;); writer.writeEndElement(); writer.writeStartElement(&quot;Address&quot;); writer.writeCharacters(&quot;1 Main Street&quot;); writer.writeEndElement(); writer.writeEndElement(); writer.writeEndElement(); writer.writeEndDocument(); writer.flush();
    43. 43. Parsing Documents with the StAX Parser Live Demo
    44. 44. Using XPath in Java Searching nodes in XML documents
    45. 45. Parsing XML Documents with XPath <ul><li>To evaluate an XPath expression in Java, create an XPath object </li></ul><ul><li>Then call the evaluate method </li></ul><ul><ul><li>expression is an XPath expression </li></ul></ul><ul><ul><li>doc is the Document object that represents the XML document </li></ul></ul>XPathFactory xpfactory = XPathFactory.newInstance(); XPath x path = xpfactory.newXPath(); String result = x path.evaluate(expression, doc)
    46. 46. Sample XML Document <ul><li><?xml version=&quot;1.0&quot; encoding=&quot;windows-1251&quot;?> </li></ul><ul><li><items culture=&quot;en-US&quot;> </li></ul><ul><li><item type=&quot;beer&quot;> </li></ul><ul><li><name>Zagorka</name> </li></ul><ul><li><price>0.54</price> </li></ul><ul><li></item> </li></ul><ul><li><item type=&quot;food&quot;> </li></ul><ul><li><name>kepab</name> </li></ul><ul><li><price>0.48</price> </li></ul><ul><li></item> </li></ul><ul><li><item type=&quot;beer&quot;> </li></ul><ul><li><name>Amstel</name> </li></ul><ul><li><price>0.56</price> </li></ul><ul><li></item> </li></ul><ul><li></items> </li></ul>
    47. 47. Parsing with XPath – Example <ul><li>For example, obtains as result the string &quot; 0.48 “ </li></ul><ul><li>XPath can also match multiple nodes and return NodeList : </li></ul>String result = xpath.evaluate(&quot;/items/item[2]/price&quot;, doc) NodeList nodes = (NodeList) xpath.evaluate( &quot;/items/item[@type='beer']/price&quot;, doc, XPathConstants.NODESET); for (int i=0; i<beerPriceNodes.getLength(); i++) { Node priceNode = nodes.item(i); System.out.println(node.getTextContent()); }
    48. 48. Using XPath Live Demo
    49. 49. Modifying XML with DOM and XPath Live Demo
    50. 50. XSL Transformations in JAXP javax.xml.transform.Transformer
    51. 51. XSLT API
    52. 52. Transforming with XSLT in Java with JAXP <ul><li>The JAXP uses a factory design pattern </li></ul><ul><ul><li>This hides the implementation classes </li></ul></ul><ul><li>The procedure for XSL transforming is: </li></ul><ul><ul><li>Create a TransformerFactory instance </li></ul></ul><ul><ul><li>Load your stylesheet into a Transformer instance </li></ul></ul><ul><ul><li>Transform your source to your output using the Transfomer instance </li></ul></ul>
    53. 53. Transforming with XSLT in Java with JAXP (2) <ul><li>Establish the factory and environment </li></ul><ul><li>Load and compile the XSL stylesheet </li></ul><ul><li>Apply the stylesheet over given document </li></ul>TransformerFactory tFactory = TransformerFactory.newInstance(); Transformer xslTransformer = tFactory.newTransformer( new StreamSource(&quot;style sheet .xsl&quot;)); xslTransformer.transform( new StreamSource(&quot;in put .xml&quot;), new Stream Result (&quot;out put .xml&quot;));
    54. 54. Transforming with XSL – Example <?xml version=&quot;1.0&quot;?> <library name=&quot;.NET Developer's Library&quot;> <book> <title>Programming Microsoft .NET</title> <author>Jeff Prosise</author> <isbn>0-7356-1376-1</isbn> </book> <book> <title>Microsoft .NET for Programmers</title> <author>Fergal Grimes</author> <isbn>1-930110-19-7</isbn> </book> </library> library.xml
    55. 55. Transforming with XSL – Example (2) <?xml version=&quot;1.0&quot; encoding=&quot;windows-1251&quot;?> <xsl:stylesheet version=&quot;1.0&quot; xmlns:xsl=&quot;http://www.w3.org/1999/XSL/Transform&quot;> <xsl:output method=&quot;xml&quot; encoding=&quot;utf-8&quot; indent=&quot;yes&quot; omit-xml-declaration=&quot;yes&quot;/> <xsl:template match=&quot;/&quot;> <html> <head> <meta http-equiv=&quot;Content-Type&quot; content=&quot;text/html; charset= utf-8 &quot; /> </head> <body> <h1>Моята библиотека</h1> <table bgcolor=&quot;#E0E0E0&quot; cellspacing=&quot;1&quot;> (example continues) library-xml2html.xsl
    56. 56. Transforming with XSL – Example (3) <tr bgcolor=&quot;#EEEEEE&quot;> <td><b>Заглавие</b></td> <td><b>Автор</b></td> </tr> <xsl:for-each select=&quot;/library/book&quot;> <tr bgcolor=&quot;white&quot;> <td><xsl:value-of select=&quot;title&quot;/></td> <td><xsl:value-of select=&quot;author&quot;/></td> </tr> </xsl:for-each> </table> </body> </html> </xsl:template> </xsl:stylesheet> library-xml2html.xsl
    57. 57. Transforming with XSL – Example (4) public class XSLTransformDemo { public static void main(String[] args) throws TransformerException { TransformerFactory tFactory = TransformerFactory.newInstance(); Transformer xslTransformer = tFactory.newTransformer( new StreamSource(&quot;library-xml2html.xsl&quot;)); xslTransformer.transform( new StreamSource(&quot; library .xml&quot;), new StreamResult(&quot; library . ht ml&quot;)); } } XSLTransformDemo.java
    58. 58. Transforming with XSL – Example (5) <html> <head> <meta http-equiv=&quot;Content-Type&quot; content=&quot;text/html; charset=utf-8&quot;/> </head> <body> <h1>Моята библиотека</h1> <table bgcolor=&quot;#E0E0E0&quot; cellspacing=&quot;1&quot;> <tr bgcolor=&quot;#EEEEEE&quot;> <td><b>Заглавие</b></td> <td><b>Автор</b></td> </tr> (example continues) Result : library.html
    59. 59. Transforming with XSL – Example (6) <tr bgcolor=&quot;white&quot;> <td>Programming Microsoft .NET</td> <td>Jeff Prosise</td> </tr> <tr bgcolor=&quot;white&quot;> <td>Microsoft .NET for Programmers</td> <td>Fergal Grimes</td> </tr> </table> </body> </html> Result : library.html
    60. 60. XSL Transformations Live Demo
    61. 61. Exercises <ul><li>Write a program that extracts from the file &quot; students.xml &quot; all available information about the students from 3-rd course (name, exams, etc.). Use the DOM parser. </li></ul><ul><li>Write a program that appends a new student &quot;Peter Petrov&quot; to the file students.xml and produces a new XML file as a result. </li></ul><ul><li>Write a program that appends a new exam to given student. The students and their exams are taken from the file students.xml and the results should be stored in a new XML file newStudents.xml . </li></ul>
    62. 62. Exercises (2) <ul><li>Write a program that extracts from the file &quot; students.xml &quot; all available information about the students from 3-rd course (name, exams, etc.). Use XPath. </li></ul><ul><li>Write a program that changes all grades for the student &quot;Peter Petrov&quot; to &quot;6&quot;. Produce a new XML file as a result. Use StAX parser. </li></ul><ul><li>Write a program that builds an XML file catalog.xml containing a catalog of books (author, title, isbn, pages). Use StAX parser. </li></ul>
    63. 63. Exercises (3) <ul><li>Using the StAX parser write a program that extracts all books' names from the file catalog .xml . </li></ul><ul><li>Using the StAX parser write a program that extracts from the students.xml all students' names. Process only students with more than one excellent grade. </li></ul><ul><li>Write an XML file containing orders. Each order is described by date, customer name and a list of order items. Each order item consists of product name, amount and price. </li></ul><ul><li>Write an XSL stylesheet to transform the XML file to a human readable XHTML document. Sort the products in alphabetical order. </li></ul>
    64. 64. Exercises (4) <ul><li>Write a JAXP based Java program to apply the XSL stylesheet over the XML document. </li></ul><ul><li>Test the produced XHTML file in your Web browser. </li></ul><ul><li>Write your CV in XML format. It should have the following structure: </li></ul><ul><ul><li>Personal information (name, DOB, ...) </li></ul></ul><ul><ul><li>Education </li></ul></ul><ul><ul><li>Skills </li></ul></ul><ul><ul><li>Work experience </li></ul></ul><ul><ul><li>... </li></ul></ul>
    65. 65. Exercises (5) <ul><li>Write a XSL stylesheet for transforming the CV to HTML and XML with other structure. Write a program to apply the stylesheet. </li></ul>
    1. A particular slide catching your eye?

      Clipping is a handy way to collect important slides you want to go back to later.

    ×