java xml programming svetlin nakov bulgarian association of software developers

65
Java XML Java XML Programming Programming Svetlin Nakov Svetlin Nakov Bulgarian Association of Bulgarian Association of Software Developers Software Developers www.devbg.org

Upload: michael-mcguire

Post on 26-Mar-2015

248 views

Category:

Documents


2 download

TRANSCRIPT

Page 1: Java XML Programming Svetlin Nakov Bulgarian Association of Software Developers

Java XML Java XML ProgrammingProgramming

Svetlin NakovSvetlin NakovBulgarian Association of Bulgarian Association of Software DevelopersSoftware Developers

www.devbg.org

Page 2: Java XML Programming Svetlin Nakov Bulgarian Association of Software Developers

ContentsContents

• Introduction to XML ParsersIntroduction to XML Parsers

• The DOM ParserThe DOM Parser

• The SAX ParserThe SAX Parser

• The StAX ParserThe StAX Parser

• Introduction to JAXPIntroduction to JAXP

• Using DOMUsing DOM

• Using StAXUsing StAX

• Java API for XPathJava API for XPath

• Java API for XSLTJava API for XSLT

Page 3: Java XML Programming Svetlin Nakov Bulgarian Association of Software Developers

XML ParsersXML Parsers

Page 4: Java XML Programming Svetlin Nakov Bulgarian Association of Software Developers

XML ParsersXML Parsers

• XML parsers are programming libraries XML parsers are programming libraries that make the work withthat make the work with XML easierXML easier

• They are used for:They are used for:

• Extracting data from XML documentsExtracting data from XML documents

• Building XML documentsBuilding XML documents

• Validating XML documents by given Validating XML documents by given schemescheme

Page 5: Java XML Programming Svetlin Nakov Bulgarian Association of Software Developers

XML Parsers – ModelsXML Parsers – Models

• DOM (Document Object Model)DOM (Document Object Model)• RepresentsRepresents XML documents as a tree XML documents as a tree

in the memoryin the memory

• Allows flexible and easy processing Allows flexible and easy processing

• Supports changing the documentSupports changing the document

• SAX (Simple API for XML Processing)SAX (Simple API for XML Processing) • ReadsReads XMLXML documents consequently (like a documents consequently (like a

stream)stream)

• Allows read-only / write-only accessAllows read-only / write-only access

• StAX (Streaming API for XML)StAX (Streaming API for XML)• Similar to SAX but simplifiedSimilar to SAX but simplified

Page 6: Java XML Programming Svetlin Nakov Bulgarian Association of Software Developers

Using a XML ParserUsing a XML Parser

• Three basic steps to using an XML parserThree basic steps to using an XML parser

• Create a parser object Create a parser object

• Pass your XML document to the parser Pass your XML document to the parser

• Process the resultsProcess the results

• Generally, writing out XML is outside Generally, writing out XML is outside scope of parsersscope of parsers

• Some parsers may implement Some parsers may implement such mechanismssuch mechanisms

Page 7: Java XML Programming Svetlin Nakov Bulgarian Association of Software Developers

Types of ParserTypes of Parser

• There are several different ways to categorize There are several different ways to categorize parsers:parsers:

• Validating versus non-validating parsers Validating versus non-validating parsers

• Parsers that support the Document Object Parsers that support the Document Object Model (DOM) Model (DOM)

• Parsers that support the Simple API for XML Parsers that support the Simple API for XML (SAX)(SAX)

• Streaming parsers (StAX)Streaming parsers (StAX)

• Parsers written in a particular language (Java, Parsers written in a particular language (Java, C#, C++, Perl, etc.)C#, C++, Perl, etc.)

Page 8: Java XML Programming Svetlin Nakov Bulgarian Association of Software Developers

The DOM ParserThe DOM Parser

Page 9: Java XML Programming Svetlin Nakov Bulgarian Association of Software Developers

DOM Parser ArchitectureDOM Parser Architecture

Page 10: Java XML Programming Svetlin Nakov Bulgarian Association of Software Developers

DOM Key FeaturesDOM Key Features

• The DOM API is generally an easier API to The DOM API is generally an easier API to useuse

• It provides a familiar tree structure of It provides a familiar tree structure of objectsobjects

• You can use it to manipulate the You can use it to manipulate the hierarchy of a XML documenthierarchy of a XML document

• The DOM API is ideal for interactive The DOM API is ideal for interactive applicationsapplications

• The entire object model is present in The entire object model is present in memorymemory

Page 11: Java XML Programming Svetlin Nakov Bulgarian Association of Software Developers

The DOMThe DOM Parser – Example Parser – Example

• TheThe following XML document is givenfollowing XML document is given::

<?xml version="1.0"?><?xml version="1.0"?><library name=".NET Developer's Library"><library name=".NET Developer's Library"> <book><book> <title>Programming Microsoft .NET</title><title>Programming Microsoft .NET</title> <author>Jeff Prosise</author><author>Jeff Prosise</author> <isbn>0-7356-1376-1</isbn><isbn>0-7356-1376-1</isbn> </book></book> <book><book> <title>Microsoft<title>Microsoft .NET for Programmers</title>.NET for Programmers</title> <author>Fergal Grimes</author><author>Fergal Grimes</author> <isbn>1-930110-19-7</isbn<isbn>1-930110-19-7</isbn>> </book></book></library></library>

Page 12: Java XML Programming Svetlin Nakov Bulgarian Association of Software Developers

The DOMThe DOM Parser – ExampleParser – Example

• This document is represented in the in the This document is represented in the in the memory as a DOM tree in the following way:memory as a DOM tree in the following way:

document

?xml library

version 1.0 encoding utf-8 book

title author isbn

Program... Jeff... O-7356...

book

title author isbn

Micros... Fergal... 1-930...

name .NET Developer’s...

Header Header partpart

Root nodeRoot node

Page 13: Java XML Programming Svetlin Nakov Bulgarian Association of Software Developers

The SAX ParserThe SAX Parser

Page 14: Java XML Programming Svetlin Nakov Bulgarian Association of Software Developers

SAX Key FeaturesSAX Key Features

• The Simple API for XML (SAX)The Simple API for XML (SAX)

• Event-drivenEvent-driven

• SSerial-access mechanism erial-access mechanism

• EElement-by-element processinglement-by-element processing

• Do not allow going backwards or Do not allow going backwards or jumping aheadjumping ahead

• Require many times less resourcesRequire many times less resources• Memory Memory

• CPU timeCPU time

• Work over streamsWork over streams

Page 15: Java XML Programming Svetlin Nakov Bulgarian Association of Software Developers

The SAX ParserThe SAX Parser

• Working with SAX is much complexWorking with SAX is much complex

• Old technologyOld technology

• Use it's new equivalent – the StAX parserUse it's new equivalent – the StAX parser

Page 16: Java XML Programming Svetlin Nakov Bulgarian Association of Software Developers

The StAX ParserThe StAX Parser

• Like SAX butLike SAX but

• Not event driven (not callback based)Not event driven (not callback based)

• "Pull"-based"Pull"-based

• Developer manually say "go to next Developer manually say "go to next element" and analyze itelement" and analyze it

• It's a new feature in Java 6.0!It's a new feature in Java 6.0!

Page 17: Java XML Programming Svetlin Nakov Bulgarian Association of Software Developers

When to UseWhen to Use DOMDOM and When to and When to Use SAX/StAX?Use SAX/StAX?

• The DOM processing model is suitable when:The DOM processing model is suitable when:

• Processing small documentsProcessing small documents

• There is a need of flexibilityThere is a need of flexibility

• There is a need of direct access to different There is a need of direct access to different nodes of the documentnodes of the document

• We need to change the documentWe need to change the document

Page 18: Java XML Programming Svetlin Nakov Bulgarian Association of Software Developers

• The SAX/StAXThe SAX/StAX processing model is suitable processing model is suitable whenwhen::

• Processing big documentsProcessing big documents

• Big XML documents (e.g. > 20-30 MB) cannot Big XML documents (e.g. > 20-30 MB) cannot be processed with DOM!be processed with DOM!

• The performance is importantThe performance is important

• There is no need to change the document There is no need to change the document nodesnodes

• SAX/StAX is read-only / write-only (like the SAX/StAX is read-only / write-only (like the streams)streams)

When to UseWhen to Use DOMDOM and When to and When to Use SAX/StAX?Use SAX/StAX?

Page 19: Java XML Programming Svetlin Nakov Bulgarian Association of Software Developers

Introduction to Introduction to JAXPJAXP

Page 20: Java XML Programming Svetlin Nakov Bulgarian Association of Software Developers

JAXPJAXP

• JJava ava AAPI for PI for XXML ML PProcessing rocessing

• Designed to be flexibleDesigned to be flexible

• FFacilitate the use of XML on the Java acilitate the use of XML on the Java platform platform

• PProvides a common interface rovides a common interface for for these standard APIsthese standard APIs

• DOMDOM

• SAX, StAXSAX, StAX

• XPathXPath and XSL Transformations (XSLT) and XSL Transformations (XSLT)

Page 21: Java XML Programming Svetlin Nakov Bulgarian Association of Software Developers

JAXP – PlugabilityJAXP – Plugability

• JAXP allows you to use any XML-JAXP allows you to use any XML-compliant parsercompliant parser

• RRegardless of which vendor's egardless of which vendor's implementation is actually being usedimplementation is actually being used

• PPluggability layerluggability layer

• LLets you plug in an implementation of ets you plug in an implementation of the SAX or DOM APIthe SAX or DOM API

• LLetetss you control how your XML data is you control how your XML data is displayeddisplayed

Page 22: Java XML Programming Svetlin Nakov Bulgarian Association of Software Developers

JAXP – IndependenceJAXP – Independence

• To achieve the goal of XML processor To achieve the goal of XML processor independenceindependence

• AApplication should limit itself to the pplication should limit itself to the JAXP APIJAXP API

• AAvoidvoid using using implementation-dependent implementation-dependent APIs and behaviorAPIs and behavior

Page 23: Java XML Programming Svetlin Nakov Bulgarian Association of Software Developers

JAXP PackagesJAXP Packages

• jjavax.xml.parsersavax.xml.parsers

• The JAXP APIsThe JAXP APIs

• PProviderovidess a common interface for a common interface for different different vendorsvendors'' SAX and DOM parsers SAX and DOM parsers

• org.w3c.domorg.w3c.dom

• Defines the Defines the DOM classesDOM classes

• Document class Document class and all and all the components the components of a DOMof a DOM

Page 24: Java XML Programming Svetlin Nakov Bulgarian Association of Software Developers

JAXP Packages (2)JAXP Packages (2)

• org.xml.saxorg.xml.sax

• Defines the basic SAX APIsDefines the basic SAX APIs

• javax.xml.streamjavax.xml.stream

• Define the basic StAX classesDefine the basic StAX classes

• javax.xml.xpathjavax.xml.xpath

• Defines API for the evaluation of XPath Defines API for the evaluation of XPath expressionsexpressions

• javax.xml.transformjavax.xml.transform

• Defines the XSLT APIs that let you transform XML Defines the XSLT APIs that let you transform XML into other formsinto other forms

Page 25: Java XML Programming Svetlin Nakov Bulgarian Association of Software Developers

Using the DOM Using the DOM ParserParser

Page 26: Java XML Programming Svetlin Nakov Bulgarian Association of Software Developers

DOM DOM DocumentDocument Structure Structure

Document+---Element <dots> +---Text "this is before the first dot | and it continues on multiple lines" +---Element <dot> +---Text "" +---Element <dot> +---Text "" +---Element <flip> | +---Text "flip is on" | +---Element <dot> | +---Text "" | +---Element <dot> | +---Text "" +---Text "flip is off" +---Element <dot> +---Text "" +---Element <extra> | +---Text "stuff" +---Text "" +---Comment "a final comment" +---Text ""

XML input:Document

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

<dots><dots> this is before the first dotthis is before the first dot and it continues on multiple linesand it continues on multiple lines <dot x="9" y="81" /><dot x="9" y="81" /> <dot x="11" y="121" /><dot x="11" y="121" /> <flip><flip> flip is onflip is on <dot x="196" y="14" /><dot x="196" y="14" /> <dot x="169" y="13" /><dot x="169" y="13" /> </flip></flip> flip is offflip is off <dot x="12" y="144" /><dot x="12" y="144" /> <extra>stuff</extra><extra>stuff</extra> <!-- a final comment --><!-- a final comment --></dots></dots>

Page 27: Java XML Programming Svetlin Nakov Bulgarian Association of Software Developers

DOM DOM DocumentDocument Structure Structure

• There’s a text node between every There’s a text node between every pair of element nodes, even if the pair of element nodes, even if the text is emptytext is empty

• XML comments appear in special XML comments appear in special comment nodescomment nodes

• Element attributes do not appear in treeElement attributes do not appear in tree

• Available through Available through ElementElement object object

Page 28: Java XML Programming Svetlin Nakov Bulgarian Association of Software Developers

DOM Classes HierarchyDOM Classes Hierarchy

Page 29: Java XML Programming Svetlin Nakov Bulgarian Association of Software Developers

Using DOMUsing DOM

import javax.xml.parsers.*;import javax.xml.parsers.*;import org.w3c.dom.*;import org.w3c.dom.*;

// // GGet a DocumentBuilder objectet a DocumentBuilder objectDocumentBuilderFactory dbf =DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();DocumentBuilderFactory.newInstance();DocumentBuilder db = null;DocumentBuilder db = null;try {try { db = dbf.newDocumentBuilder();db = dbf.newDocumentBuilder();} catch (ParserConfigurationException e) {} catch (ParserConfigurationException e) { e.printStackTrace();e.printStackTrace();}}

// // IInvoke parser to get a Documentnvoke parser to get a DocumentDocument doc = db.parse(inputStream);Document doc = db.parse(inputStream);Document doc = db.parse(file);Document doc = db.parse(file);Document doc = db.parse(url);Document doc = db.parse(url);

Here’s the basic recipe for getting started:Here’s the basic recipe for getting started:

Page 30: Java XML Programming Svetlin Nakov Bulgarian Association of Software Developers

DOM DOM DocumentDocument Access Idioms Access Idioms

// get the root of the Document treeElement root = doc.getDocumentElement();

// get nodes in subtree by tag nameNodeList dots = root.getElementsByTagName("dot");

// get first dot elementElement firstDot = (Element) dots.item(0);

// get x attribute of first dotString x = firstDot.getAttribute("x");

• OK, say we have a OK, say we have a DocumentDocument. How do we get at the . How do we get at the pieces of it?pieces of it?

• Here are some common idioms:Here are some common idioms:

Page 31: Java XML Programming Svetlin Nakov Bulgarian Association of Software Developers

More More DocumentDocument Accessors Accessors

NodeNode access methods:access methods:

StringString getNodeNamegetNodeName()()shortshort getNodeTypegetNodeType()()DocumentDocument getOwnerDocumentgetOwnerDocument()()booleanboolean hasChildNodeshasChildNodes()()NodeListNodeList getChildNodesgetChildNodes()()NodeNode getFirstChildgetFirstChild()()NodeNode getLastChildgetLastChild()()NodeNode getParentNodegetParentNode()()NodeNode getNextSiblinggetNextSibling()()NodeNode getPreviousSiblinggetPreviousSibling()()booleanboolean hasAttributeshasAttributes()()... and more ...... and more ...

e.g. e.g. DOCUMENT_NODE, DOCUMENT_NODE, ELEMENT_NODE, ELEMENT_NODE,

TEXT_NODE, TEXT_NODE, COMMENT_NODE, COMMENT_NODE,

etc.etc.

Page 32: Java XML Programming Svetlin Nakov Bulgarian Association of Software Developers

More More DocumentDocument Accessors Accessors

ElementElement extendsextends NodeNode and adds these and adds these access methods:access methods:

StringString getTagNamegetTagName()()booleanboolean hasAttributehasAttribute((StringString namename))StringString getAttributegetAttribute((StringString namename))NodeListNodeList getElementsByTagNamegetElementsByTagName((StringString namename))… … and more …and more …

DocumentDocument extendsextends NodeNode and adds these and adds these access methods:access methods:

ElementElement getDocumentElementgetDocumentElement()()DocumentTypeDocumentType getDoctypegetDoctype()()... plus the... plus the ElementElement methods just mentioned ...methods just mentioned ...... and more ...... and more ...

Page 33: Java XML Programming Svetlin Nakov Bulgarian Association of Software Developers

Writing a Writing a DocumentDocument as XML as XML

• JAXP do not specify how to write XML JAXP do not specify how to write XML document to a filedocument to a file

• Most JAXP implementations have own Most JAXP implementations have own classes for writing XML filesclasses for writing XML files

• E.g. the class E.g. the class XMLSerializerXMLSerializer in Apache in Apache Xerces (the standard parser in J2SE 5.0)Xerces (the standard parser in J2SE 5.0)

import com.sun.org.apache.xml.internal.import com.sun.org.apache.xml.internal. serialize.XMLSerializer;serialize.XMLSerializer;XMLSerializer xmlser = new XMLSerializer();XMLSerializer xmlser = new XMLSerializer();xmlser.setOutputByteStream(System.out);xmlser.setOutputByteStream(System.out);xmlser.serialize(doc);xmlser.serialize(doc);

Page 34: Java XML Programming Svetlin Nakov Bulgarian Association of Software Developers

Reading and Parsing Reading and Parsing XML Documents XML Documents

with the DOM Parserwith the DOM ParserLive DemoLive Demo

Page 35: Java XML Programming Svetlin Nakov Bulgarian Association of Software Developers

Creating & Manipulating DOM Creating & Manipulating DOM DocumentsDocuments

// Get new empty Document from DocumentBuilder// Get new empty Document from DocumentBuilderDocument doc = docBuilder.newDocument();Document doc = docBuilder.newDocument();

// Create a new <dots> element// Create a new <dots> element// and add it to the document as root// and add it to the document as rootElement root = doc.createElement("dots");Element root = doc.createElement("dots");doc.appendChild(root);doc.appendChild(root);

// Create a new <dot> element// Create a new <dot> element// and add as child of the root// and add as child of the rootElement dot = doc.createElement("dot");Element dot = doc.createElement("dot");dot.setAttribute("x", "9");dot.setAttribute("x", "9");dot.setAttribute("y", "81");dot.setAttribute("y", "81");root.appendChild(dot);root.appendChild(dot);

• The DOM API also includes lots of methods for The DOM API also includes lots of methods for creating and manipulating creating and manipulating DocumentDocument objects: objects:

Page 36: Java XML Programming Svetlin Nakov Bulgarian Association of Software Developers

More More DocumentDocument Manipulators Manipulators

NodeNode manipulation methods:manipulation methods:

voidvoid setNodeValuesetNodeValue((StringString nodeValuenodeValue))NodeNode appendChildappendChild((NodeNode newChildnewChild))NodeNode insertBeforeinsertBefore((NodeNode newChildnewChild, , NodeNode refChildrefChild))NodeNode removeChildremoveChild((NodeNode oldChildoldChild))... and more ...... and more ...

ElementElement manipulation methods:manipulation methods:

voidvoid setAttributesetAttribute((StringString namename, , StringString valuevalue))voidvoid removeAttributeremoveAttribute((StringString namename))… … and more …and more …

DocumentDocument manipulation methods:manipulation methods:

TextText createTextNodecreateTextNode((StringString datadata))CommentComment createCommentNodecreateCommentNode((StringString datadata))... and more ...... and more ...

Page 37: Java XML Programming Svetlin Nakov Bulgarian Association of Software Developers

Building Documents Building Documents with the DOM Parserwith the DOM Parser

Live DemoLive Demo

Page 38: Java XML Programming Svetlin Nakov Bulgarian Association of Software Developers

Using TheUsing TheStAX ParserStAX Parser

Page 39: Java XML Programming Svetlin Nakov Bulgarian Association of Software Developers

The StAX Parser in JavaThe StAX Parser in Java

• As from Java 6 the StAX parser is As from Java 6 the StAX parser is available as part of Javaavailable as part of Java

• Two basic StAX classesTwo basic StAX classes

•XMLStreamReaderXMLStreamReader• Pull based XML streaming API for parsing Pull based XML streaming API for parsing

XML documents – read-onlyXML documents – read-only

•XMLStreamWriterXMLStreamWriter• Streaming based builder for XML Streaming based builder for XML

documents – write-onlydocuments – write-only

Page 40: Java XML Programming Svetlin Nakov Bulgarian Association of Software Developers

Parsing Documents withParsing Documents with thethe StAX Parser – ExampleStAX Parser – Example

FileReader fileReader = new FileReader fileReader = new FileReader("Student.xml");FileReader("Student.xml");XMLInputFactory factory =XMLInputFactory factory = XMLInputFactory.XMLInputFactory.newInstancenewInstance();();XMLStreamReader reader =XMLStreamReader reader = factory.createXMLStreamReader(fileReader);factory.createXMLStreamReader(fileReader);String element = "";String element = "";while (reader.hasNext()) {while (reader.hasNext()) { if (reader.isStartElement()) {if (reader.isStartElement()) { element = reader.getLocalName();element = reader.getLocalName(); } else if (reader.isCharacters() && } else if (reader.isCharacters() &&

!reader.isWhiteSpace()) {!reader.isWhiteSpace()) { System.System.outout.printf("%s - %s%n", element, .printf("%s - %s%n", element,

reader.getText());reader.getText()); }} reader.next();reader.next();}}reader.close()reader.close()

Page 41: Java XML Programming Svetlin Nakov Bulgarian Association of Software Developers

Parsing Documents Parsing Documents withwith thethe StAX Parser StAX Parser

Live DemoLive Demo

Page 42: Java XML Programming Svetlin Nakov Bulgarian Association of Software Developers

Creating Documents withCreating Documents with thethe StAX Parser – ExampleStAX Parser – Example

String fileName = "Customers.xml";String fileName = "Customers.xml";FileWriter fileWriter = new FileWriter(fileName); FileWriter fileWriter = new FileWriter(fileName); XMLOutputFactory factory =XMLOutputFactory factory = XMLOutputFactory.XMLOutputFactory.newInstancenewInstance();();XMLStreamWriter writer =XMLStreamWriter writer = factory.createXMLStreamWriter(fileWriter);factory.createXMLStreamWriter(fileWriter);writer.writeStartDocument();writer.writeStartDocument(); writer.writeStartElement("Customers");writer.writeStartElement("Customers"); writer.writeStartElement("Customer");writer.writeStartElement("Customer"); writer.writeStartElement("Name");writer.writeStartElement("Name"); writer.writeCharacters("ABC Pizza");writer.writeCharacters("ABC Pizza"); writer.writeEndElement();writer.writeEndElement(); writer.writeStartElement("Address");writer.writeStartElement("Address"); writer.writeCharacters("1 Main Street");writer.writeCharacters("1 Main Street"); writer.writeEndElement();writer.writeEndElement(); writer.writeEndElement();writer.writeEndElement(); writer.writeEndElement();writer.writeEndElement(); writer.writeEndDocument();writer.writeEndDocument();writer.flush();writer.flush();

Page 43: Java XML Programming Svetlin Nakov Bulgarian Association of Software Developers

Parsing Documents Parsing Documents withwith thethe StAX Parser StAX Parser

Live DemoLive Demo

Page 44: Java XML Programming Svetlin Nakov Bulgarian Association of Software Developers

Using XPath in JavaUsing XPath in JavaSearching nodes in XML documentsSearching nodes in XML documents

Page 45: Java XML Programming Svetlin Nakov Bulgarian Association of Software Developers

Parsing XML Documents Parsing XML Documents with XPathwith XPath

• To evaluate an XPath expression in Java, To evaluate an XPath expression in Java, create an XPath objectcreate an XPath object

• Then call the Then call the evaluateevaluate method method

• expressionexpression is an XPath expression is an XPath expression

• docdoc is the is the DocumentDocument object that represents object that represents the XML documentthe XML document

XPathFactory xpfactory = XPathFactory.newInstance(); XPathFactory xpfactory = XPathFactory.newInstance(); XPath XPath xxpath = xpfactory.newXPath();path = xpfactory.newXPath();

String result = String result = xxpath.evaluate(expression, doc)path.evaluate(expression, doc)

Page 46: Java XML Programming Svetlin Nakov Bulgarian Association of Software Developers

Sample XML DocumentSample XML Document

<?xml version="1.0" encoding="windows-1251"?><?xml version="1.0" encoding="windows-1251"?>

<items culture="en-US"><items culture="en-US"> <item type="beer"><item type="beer"> <name>Zagorka</name><name>Zagorka</name> <price>0.54</price><price>0.54</price> </item></item> <item type="food"><item type="food"> <name>kepab</name><name>kepab</name> <price>0.48</price><price>0.48</price> </item></item> <item type="beer"><item type="beer"> <name>Amstel</name><name>Amstel</name> <price>0.56</price><price>0.56</price> </item></item></items></items>

Page 47: Java XML Programming Svetlin Nakov Bulgarian Association of Software Developers

Parsing with XPath – Parsing with XPath – ExampleExample

• For example,For example,

obtains as result the string "obtains as result the string "0.480.48““

• XPath can also match multiple nodes and XPath can also match multiple nodes and return return NodeListNodeList::

String result =String result = xpath.evaluate("/items/item[2]/price", doc) xpath.evaluate("/items/item[2]/price", doc)

NodeList nodes = (NodeList) xpath.evaluate(NodeList nodes = (NodeList) xpath.evaluate( "/items/item[@type='beer']/price", doc,"/items/item[@type='beer']/price", doc, XPathConstants.NODESET);XPathConstants.NODESET);for (int i=0; i<beerPriceNodes.getLength(); i++) {for (int i=0; i<beerPriceNodes.getLength(); i++) { Node priceNode = nodes.item(i);Node priceNode = nodes.item(i); System.out.println(node.getTextContent());System.out.println(node.getTextContent());}}

Page 48: Java XML Programming Svetlin Nakov Bulgarian Association of Software Developers

Using XPathUsing XPathLive DemoLive Demo

Page 49: Java XML Programming Svetlin Nakov Bulgarian Association of Software Developers

Modifying XML with Modifying XML with DOM and XPathDOM and XPath

Live DemoLive Demo

Page 50: Java XML Programming Svetlin Nakov Bulgarian Association of Software Developers

XSL Transformations XSL Transformations in JAXPin JAXP

javax.xml.transform.Transformerjavax.xml.transform.Transformer

Page 51: Java XML Programming Svetlin Nakov Bulgarian Association of Software Developers

XSLT APIXSLT API

Page 52: Java XML Programming Svetlin Nakov Bulgarian Association of Software Developers

Transforming with XSLT in Transforming with XSLT in Java with JAXPJava with JAXP

• The JAXP uses a factory design patternThe JAXP uses a factory design pattern

• This hides the implementation classesThis hides the implementation classes

• The procedure for XSL transforming is:The procedure for XSL transforming is:

1.1. Create a Create a TransformerFactoryTransformerFactory instanceinstance

2.2. Load your stylesheet into a Load your stylesheet into a TransformerTransformer instance instance

3.3. Transform your source to your output Transform your source to your output using the using the TransfomerTransfomer instance instance

Page 53: Java XML Programming Svetlin Nakov Bulgarian Association of Software Developers

Transforming with XSLT in Transforming with XSLT in Java with JAXP (2)Java with JAXP (2)

1.1. Establish the factoryEstablish the factory and and environmentenvironment

2.2. Load and compile the Load and compile the XSL XSL stylesheetstylesheet

3.3. Apply the Apply the stylesheet over given documentstylesheet over given document

TransformerFactory tFactory =TransformerFactory tFactory = TransformerFactory.newInstance();TransformerFactory.newInstance();

Transformer xslTransformer =Transformer xslTransformer = tFactory.newTransformer(tFactory.newTransformer( new StreamSource("stylenew StreamSource("stylesheetsheet.xsl"));.xsl"));

xslTransformer.transform(xslTransformer.transform( new StreamSource("innew StreamSource("inputput.xml"),.xml"), new Streamnew StreamResultResult("out("outputput.xml"));.xml"));

Page 54: Java XML Programming Svetlin Nakov Bulgarian Association of Software Developers

Transforming with XSL – Transforming with XSL – ExampleExample

<?xml version="1.0"?><?xml version="1.0"?><library name=".NET Developer's Library"><library name=".NET Developer's Library"> <book><book> <title>Programming Microsoft .NET</title><title>Programming Microsoft .NET</title> <author>Jeff Prosise</author><author>Jeff Prosise</author> <isbn>0-7356-1376-1</isbn><isbn>0-7356-1376-1</isbn> </book></book> <book><book> <title>Microsoft .NET for Programmers</title><title>Microsoft .NET for Programmers</title> <author>Fergal Grimes</author><author>Fergal Grimes</author> <isbn>1-930110-19-7</isbn><isbn>1-930110-19-7</isbn> </book></book></library></library>

library.xmllibrary.xmllibrary.xmllibrary.xml

Page 55: Java XML Programming Svetlin Nakov Bulgarian Association of Software Developers

Transforming with XSL – Transforming with XSL – Example (2)Example (2)

<?xml version="1.0" encoding="windows-1251"?><?xml version="1.0" encoding="windows-1251"?><xsl:stylesheet version="1.0"<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">xmlns:xsl="http://www.w3.org/1999/XSL/Transform"><xsl:output method="xml" encoding="utf-8"<xsl:output method="xml" encoding="utf-8" indent="yes" omit-xml-declaration="yes"/>indent="yes" omit-xml-declaration="yes"/><xsl:template match="/"><xsl:template match="/"> <html><html> <head><head> <meta http-equiv="Content-Type"<meta http-equiv="Content-Type" content="text/html; charset=content="text/html; charset=utf-8utf-8" />" /> </head></head> <body><body> <h1>Моята библиотека</h1><h1>Моята библиотека</h1> <table bgcolor="#E0E0E0" cellspacing="1"><table bgcolor="#E0E0E0" cellspacing="1">

(example continues)(example continues)

library-xml2html.xsllibrary-xml2html.xsllibrary-xml2html.xsllibrary-xml2html.xsl

Page 56: Java XML Programming Svetlin Nakov Bulgarian Association of Software Developers

<tr bgcolor="#EEEEEE"><tr bgcolor="#EEEEEE"> <td><b>Заглавие</b></td><td><b>Заглавие</b></td> <td><b>Автор</b></td><td><b>Автор</b></td> </tr></tr> <xsl:for-each select="/library/book"><xsl:for-each select="/library/book"> <tr bgcolor="white"><tr bgcolor="white"> <td><xsl:value-of select="title"/></td><td><xsl:value-of select="title"/></td> <td><xsl:value-of select="author"/></td><td><xsl:value-of select="author"/></td> </tr></tr> </xsl:for-each></xsl:for-each> </table></table> </body></body> </html></html></xsl:template></xsl:template></xsl:stylesheet></xsl:stylesheet>

library-xml2html.xsllibrary-xml2html.xsllibrary-xml2html.xsllibrary-xml2html.xsl

Transforming with XSL – Transforming with XSL – Example (3)Example (3)

Page 57: Java XML Programming Svetlin Nakov Bulgarian Association of Software Developers

Transforming with XSL – Transforming with XSL – Example (4)Example (4)

public class XSLTransformDemo {public class XSLTransformDemo { public static void main(String[] args) public static void main(String[] args) throws TransformerException {throws TransformerException { TransformerFactory tFactory =TransformerFactory tFactory = TransformerFactory.newInstance();TransformerFactory.newInstance(); Transformer xslTransformer =Transformer xslTransformer = tFactory.newTransformer(tFactory.newTransformer( new StreamSource("library-xml2html.xsl"));new StreamSource("library-xml2html.xsl")); xslTransformer.transform(xslTransformer.transform( new StreamSource("new StreamSource("librarylibrary.xml"),.xml"), new StreamResult("new StreamResult("librarylibrary..hthtml"));ml")); }}}}

XSLTransformDemo.javaXSLTransformDemo.javaXSLTransformDemo.javaXSLTransformDemo.java

Page 58: Java XML Programming Svetlin Nakov Bulgarian Association of Software Developers

Transforming with XSL – Transforming with XSL – Example (5)Example (5)

<html><html><head><head> <meta http-equiv="Content-Type"<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>content="text/html; charset=utf-8"/></head></head><body><body> <h1>Моята библиотека</h1><h1>Моята библиотека</h1> <table bgcolor="#E0E0E0" cellspacing="1"><table bgcolor="#E0E0E0" cellspacing="1"> <tr bgcolor="#EEEEEE"><tr bgcolor="#EEEEEE"> <td><b>Заглавие</b></td><td><b>Заглавие</b></td> <td><b>Автор</b></td><td><b>Автор</b></td> </tr></tr>

(example continues)(example continues)

ResultResult: library.html: library.htmlResultResult: library.html: library.html

Page 59: Java XML Programming Svetlin Nakov Bulgarian Association of Software Developers

Transforming with XSL – Transforming with XSL – Example (6)Example (6)

<tr bgcolor="white"><tr bgcolor="white"> <td>Programming Microsoft .NET</td><td>Programming Microsoft .NET</td> <td>Jeff Prosise</td><td>Jeff Prosise</td> </tr></tr> <tr bgcolor="white"><tr bgcolor="white"> <td>Microsoft .NET for Programmers</td><td>Microsoft .NET for Programmers</td> <td>Fergal Grimes</td><td>Fergal Grimes</td> </tr></tr> </table></table></body></body></html></html>

ResultResult: library.html: library.htmlResultResult: library.html: library.html

Page 60: Java XML Programming Svetlin Nakov Bulgarian Association of Software Developers

XSL TransformationsXSL TransformationsLive DemoLive Demo

Page 61: Java XML Programming Svetlin Nakov Bulgarian Association of Software Developers

ExercisesExercises

1.1. Write a program that extracts from the file Write a program that extracts from the file ""students.xmlstudents.xml" all available information " all available information about the students from 3-rd course (name, about the students from 3-rd course (name, exams, etc.). Use the DOM parser.exams, etc.). Use the DOM parser.

2.2. Write a program that appends a new student Write a program that appends a new student "Peter Petrov" to the file "Peter Petrov" to the file students.xmlstudents.xml and and produces a new XML file as a result.produces a new XML file as a result.

3.3. Write a program that appends a new exam to Write a program that appends a new exam to given student. The students and their exams given student. The students and their exams are taken from the file are taken from the file students.xmlstudents.xml and the and the results should be stored in a new XML file results should be stored in a new XML file newStudents.xmlnewStudents.xml..

Page 62: Java XML Programming Svetlin Nakov Bulgarian Association of Software Developers

Exercises (2)Exercises (2)

4.4. Write a program that extracts from the file Write a program that extracts from the file ""students.xmlstudents.xml" all available information " all available information about the students from 3-rd course (name, about the students from 3-rd course (name, exams, etc.). Use XPath. exams, etc.). Use XPath.

5.5. Write a program that changes all grades Write a program that changes all grades for the student "Peter Petrov" to "6". for the student "Peter Petrov" to "6". Produce a new XML file as a result. Use Produce a new XML file as a result. Use StAX parser. StAX parser.

6.6. Write a program that builds an XML file Write a program that builds an XML file catalog.xmlcatalog.xml containing a catalog of containing a catalog of books (author, title, isbn, pages). Use books (author, title, isbn, pages). Use StAX parser.StAX parser.

Page 63: Java XML Programming Svetlin Nakov Bulgarian Association of Software Developers

Exercises (3)Exercises (3)

7.7. Using the StAX parser write a program that Using the StAX parser write a program that extracts all books' names from the file extracts all books' names from the file catalogcatalog.xml.xml..

8.8. Using the StAX parser write a program that Using the StAX parser write a program that extracts from the extracts from the students.xmlstudents.xml all students' all students' names. Process only students with more than names. Process only students with more than one excellent grade.one excellent grade.

9.9. Write an XML file containing orders. Each order Write an XML file containing orders. Each order is described by date, customer name and a list is described by date, customer name and a list of order items. Each order item consists of of order items. Each order item consists of product name, amount and price. product name, amount and price.

10.10. Write an XSL stylesheet to transform the XML Write an XSL stylesheet to transform the XML file to a human readable XHTML document. Sort file to a human readable XHTML document. Sort the products in alphabetical order.the products in alphabetical order.

Page 64: Java XML Programming Svetlin Nakov Bulgarian Association of Software Developers

Exercises (4)Exercises (4)

11.11. Write a JAXP based Java program to apply Write a JAXP based Java program to apply the XSL stylesheet over the XML document.the XSL stylesheet over the XML document.

12.12. Test the produced XHTML file in your Web Test the produced XHTML file in your Web browser.browser.

13.13. Write your CV in XML format. It should have Write your CV in XML format. It should have the following structure:the following structure:• Personal information (name, DOB, ...)Personal information (name, DOB, ...)• EducationEducation• SkillsSkills• Work experienceWork experience• ......

Page 65: Java XML Programming Svetlin Nakov Bulgarian Association of Software Developers

Exercises (5)Exercises (5)

14.14. Write a XSL stylesheet for transforming the CV Write a XSL stylesheet for transforming the CV to HTML and XML with other structure. Write a to HTML and XML with other structure. Write a program to apply the stylesheet.program to apply the stylesheet.