XML Parsing Atul Kahate [email_address]
XML Processing <ul><li>XML processing means </li></ul><ul><ul><li>Reading an XML document  </li></ul></ul><ul><ul><li>Pars...
XML Parser <ul><li>Software that sits between an application and the XML files </li></ul><ul><li>Shield programmers from h...
XML Processing Approaches <ul><li>Process as a sequence of events </li></ul><ul><ul><li>Simple API for XML Processing (SAX...
SAX Versus DOM
StAX <ul><li>Pulls events from the XML document via the parser </li></ul><ul><li>Also an event-based API, but differs from...
Simple API for XML (SAX)
XML Processing as Sequence of Events – 1 <ul><li>Process as a sequence of events </li></ul><ul><ul><li>Event is the occurr...
XML Processing as Sequence of Events – 2 <ul><li>Process as a sequence of events </li></ul><ul><ul><li>Event-based model c...
XML Processing as Sequence of Events – 3 <ul><li>Process as a sequence of events </li></ul><ul><ul><li>The programmer has ...
Sequential Processing Example – 1 <ul><li>Consider the following XML document </li></ul><ul><li><?xml version=“1.0”?> </li...
Sequential Processing Example – 2 <ul><li>Events generated when we read the above XML file </li></ul><ul><li>Start documen...
Sample XML Tree
Tree Processing Sequence 1 2 8 3 4 9 10 14 15 5 6 7 11 12 13 16 17
Sequential Traversal: Summary <ul><li>Order </li></ul><ul><ul><li>Top to bottom </li></ul></ul><ul><ul><li>Left to right <...
SAX Concept
JAXP Java API for XML Processing
JAXP Concept Application program written in Java for working with XML Java API for XML Processing (JAXP) JAXP APIs Simple ...
JAXP <ul><li>Java API for XML Processing </li></ul><ul><li>Standardized by Sun </li></ul><ul><li>Very thin layer on top of...
JAXP: API or Abstraction? <ul><li>JAXP is an API, but is called as an abstraction layer </li></ul><ul><ul><li>Does not pro...
JAXP and Parsing <ul><li>JAXP is  not  a replacement for SAX, DOM, JDOM etc </li></ul><ul><li>Some vendor must supply the ...
JAXP API <ul><li>The main JAXP APIs are defined in the package javax.xml.parsers </li></ul><ul><li>Contains two vendor-neu...
Package Details <ul><li>javax.xml.parsers   </li></ul><ul><ul><li>The JAXP APIs, which provide a common interface for diff...
Which Packages to use in JAXP? <ul><li>We need to include two sets of packages – one for JAXP and the other for SAX/DOM, a...
SAX Programming in JAXP
SAX Approach
Key SAX APIs – 1 <ul><li>SAXParserFactory   </li></ul><ul><ul><li>Creates an instance of the parser determined by the syst...
Key SAX APIs – 2 <ul><li>SAXReader   </li></ul><ul><ul><li>The SAXParser wraps a SAXReader. Typically, you don't care abou...
1 – Specify the Parser <ul><li>Various approaches are possible </li></ul><ul><ul><li>Set a system property for javax.xml.p...
1 – Specify the Parser <ul><li>Example </li></ul><ul><li>Public static void main (String [] args) </li></ul><ul><li>{ </li...
2 – Create a Parser Instance <ul><li>Steps </li></ul><ul><ul><li>Create an instance of a parser factory </li></ul></ul><ul...
3 – Create an Event Handler <ul><li>Event handler responds to parsing events </li></ul><ul><ul><li>It is a subclass of Def...
3 – Create an Event Handler <ul><li>Example method: startElement </li></ul><ul><li>Declaration </li></ul><ul><li>public vo...
3 – Create an Event Handler <ul><li>nameSpaceURI </li></ul><ul><li><cwp:book xmlns:cwp= “http://www.test.com/xml/”> </li><...
4 – Invoke the Parser <ul><li>Call the  parse  method, supplying: </li></ul><ul><ul><li>The content handler </li></ul></ul...
Sample XML File (emp.xml) <ul><li><?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?> </li></ul><ul><li><root> </li...
Java Program to Count Total Number of Elements <ul><li>import javax.xml.parsers.SAXParser; </li></ul><ul><li>import javax....
Count Only  Book  Elements <ul><li><?xml version=&quot;1.0&quot;?> </li></ul><ul><li><books> </li></ul><ul><li><book categ...
Parsing Code in JAXP <ul><li>import java.io.IOException; </li></ul><ul><li>import java.lang.*; </li></ul><ul><li>import ja...
Specifying Parser Name <ul><li>import java.io.IOException; </li></ul><ul><li>import javax.xml.parsers.SAXParser; </li></ul...
Exercise <ul><li>Consider the following XML file and write a program to count the number of elements that have at least on...
Solution <ul><li>import java.io.IOException; </li></ul><ul><li>import javax.xml.parsers.SAXParser; </li></ul><ul><li>impor...
Exercise <ul><li>For the same XML file, display element names only if the book is published in the 1970s. </li></ul>
Solution <ul><li>import java.io.IOException; </li></ul><ul><li>import java.lang.*; </li></ul><ul><li>import javax.xml.pars...
Exercise <ul><li>Consider the following XML document (stock.xml) </li></ul><ul><li><?xml version=&quot;1.0&quot;?> </li></...
Expected Output
Solution <ul><li>import java.io.*; </li></ul><ul><li>import org.xml.sax.*; </li></ul><ul><li>import org.xml.sax.helpers.*;...
Exercise <ul><li>Consider the following XML document. Write a Java program to find out the maximum price, and also display...
Solution <ul><li>package saxexamples; </li></ul><ul><li>import javax.xml.parsers.SAXParser; </li></ul><ul><li>import javax...
Exercise <ul><li>Consider the following XML file and write a program to find out and display the total cost for all CDs. <...
Solution <ul><li>import java.io.IOException; </li></ul><ul><li>import java.lang.*; </li></ul><ul><li>import javax.xml.pars...
Document Object Model (DOM)
DOM – Basic Flow
Basic Concepts
JAXP and DOM – Overview <ul><li>Class DocumentBuilderFactory </li></ul><ul><ul><li>public abstract class javax.xml.parsers...
JAXP and DOM – Overview <ul><li>Class DocumentBuilder </li></ul><ul><ul><li>public abstract class javax.xml.parsers. Docum...
JAXP and DOM – Overview <ul><li>Interface Document </li></ul><ul><ul><li>public interface Document extends Node </li></ul>...
JAXP and DOM – Overview <ul><li>Interface Element </li></ul><ul><ul><li>public interface Element extends Node </li></ul></...
JAXP and DOM <ul><li>DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance (); </li></ul><ul><li>DocumentBui...
Example – XML File <ul><li>Count the number of Employee elements from this XML using DOM </li></ul><ul><li><?xml version=&...
Example – Java Code <ul><li>/* </li></ul><ul><li>* To change this template, choose Tools | Templates </li></ul><ul><li>* a...
Case Study – XML File <ul><li><?xml version=&quot;1.0&quot;?> </li></ul><ul><li><catalog> </li></ul><ul><li><cd> </li></ul...
Problem <ul><li>Write a program to find out if an element by the name price exists in the XML file and display its content...
Solution <ul><li>package domexamples; </li></ul><ul><li>import org.w3c.dom.*; </li></ul><ul><li>import org.w3c.dom.bootstr...
Problem <ul><li>Write a program to display element names and their attribute names and values </li></ul>
Solution <ul><li>package domexamples; </li></ul><ul><li>import org.w3c.dom.*; </li></ul><ul><li>import org.w3c.dom.bootstr...
Problem <ul><li>For a given element, find out all the child elements and display their types </li></ul>
Solution <ul><li>import org.w3c.dom.*; </li></ul><ul><li>package domexamples; </li></ul><ul><li>import org.w3c.dom.*; </li...
Node Types <ul><li>1 ELEMENT_NODE Element The element name  2 ATTRIBUTE_NODE Attribute The attribute name  3 TEXT_NODE Tex...
Problem <ul><li>Write a program to create XML contents dynamically and write them to a file on the disk </li></ul>
Solution <ul><li>/* </li></ul><ul><li>* To change this template, choose Tools | Templates </li></ul><ul><li>* and open the...
Stream API (StAX)
Creating an XML Document using StAX <ul><li>package xmlbook.chapter7; </li></ul><ul><li>import java.io.*; </li></ul><ul><l...
Using StAX to Read <ul><li>package xmlbook.chapter7; </li></ul><ul><li>import java.io.*; </li></ul><ul><li>import java.uti...
XML and ASP.NET – An Overview
XmlReader and XmlWriter <ul><li>XMLReader </li></ul><ul><ul><li>Pull-style API for XML </li></ul></ul><ul><ul><li>Forward-...
Example – XML Document <ul><li><? xml   version =&quot;1.0&quot;  encoding =&quot;utf-8&quot; ?> </li></ul><ul><li>< books...
Example – ASP.NET Page <ul><li>using System; </li></ul><ul><li>using System.Data; </li></ul><ul><li>using System.Configura...
Validating an XML Against a Schema <ul><li>using System.Xml.Schema; </li></ul><ul><li>using System; </li></ul><ul><li>usin...
Creating an XML Document <ul><li>using System.Xml.Schema; </li></ul><ul><li>using System; </li></ul><ul><li>using System.X...
Thank you! Any Questions?
Upcoming SlideShare
Loading in...5
×

5 xml parsing

1,024

Published on

XML Parsing

Published in: Education, Technology
1 Comment
0 Likes
Statistics
Notes
  • i want code in ios
       Reply 
    Are you sure you want to  Yes  No
    Your message goes here
  • Be the first to like this

No Downloads
Views
Total Views
1,024
On Slideshare
0
From Embeds
0
Number of Embeds
0
Actions
Shares
0
Downloads
54
Comments
1
Likes
0
Embeds 0
No embeds

No notes for slide

5 xml parsing

  1. 1. XML Parsing Atul Kahate [email_address]
  2. 2. XML Processing <ul><li>XML processing means </li></ul><ul><ul><li>Reading an XML document </li></ul></ul><ul><ul><li>Parsing it in the desired manner </li></ul></ul><ul><li>Allows handling the contents of an XML document the way we want </li></ul>
  3. 3. XML Parser <ul><li>Software that sits between an application and the XML files </li></ul><ul><li>Shield programmers from having to manually parse through XML documents </li></ul><ul><li>Programmers are free to concentrate on the contents of the XML file, not syntax </li></ul><ul><li>Programmers use the parser APIs to access/manipulate an XML file </li></ul>
  4. 4. XML Processing Approaches <ul><li>Process as a sequence of events </li></ul><ul><ul><li>Simple API for XML Processing (SAX) </li></ul></ul><ul><li>Process as a hierarchy of nodes </li></ul><ul><ul><li>Document Object Model (DOM) </li></ul></ul><ul><li>Pull approach </li></ul><ul><ul><li>Streaming API (StAX) </li></ul></ul>
  5. 5. SAX Versus DOM
  6. 6. StAX <ul><li>Pulls events from the XML document via the parser </li></ul><ul><li>Also an event-based API, but differs from SAX </li></ul><ul><ul><li>The application, and not the parser; controls the flow </li></ul></ul>
  7. 7. Simple API for XML (SAX)
  8. 8. XML Processing as Sequence of Events – 1 <ul><li>Process as a sequence of events </li></ul><ul><ul><li>Event is the occurrence of something noticeable </li></ul></ul><ul><ul><li>e.g. in Windows, mouse movement, keyboard input are events </li></ul></ul><ul><ul><li>The OS captures all events and sends messages to a program </li></ul></ul><ul><ul><li>The programmer has to take an appropriate action to deal with the event </li></ul></ul>
  9. 9. XML Processing as Sequence of Events – 2 <ul><li>Process as a sequence of events </li></ul><ul><ul><li>Event-based model can be applied to XML documents also </li></ul></ul><ul><ul><li>Various events that occur while reading an XML document sequentially </li></ul></ul><ul><ul><ul><li>Start of document </li></ul></ul></ul><ul><ul><ul><li>Start tag of an element </li></ul></ul></ul><ul><ul><ul><li>End tag of an element </li></ul></ul></ul><ul><ul><ul><li>Comments </li></ul></ul></ul>
  10. 10. XML Processing as Sequence of Events – 3 <ul><li>Process as a sequence of events </li></ul><ul><ul><li>The programmer has to write code to handle these events </li></ul></ul><ul><ul><li>Called as event handlers </li></ul></ul>
  11. 11. Sequential Processing Example – 1 <ul><li>Consider the following XML document </li></ul><ul><li><?xml version=“1.0”?> </li></ul><ul><li><books> </li></ul><ul><li><book> </li></ul><ul><li><name> Learning XML </name> </li></ul><ul><li><author> Simon North </author> </li></ul><ul><li><publication> TMH </publication> </li></ul><ul><li></book> </li></ul><ul><li><book> </li></ul><ul><li><name> XML by Example </name> </li></ul><ul><li><author> Don Box </author> </li></ul><ul><li><publication> Pearson </publication> </li></ul><ul><li></book> </li></ul><ul><li></books> </li></ul>
  12. 12. Sequential Processing Example – 2 <ul><li>Events generated when we read the above XML file </li></ul><ul><li>Start document </li></ul><ul><li>Start element: books </li></ul><ul><li>Start element: book </li></ul><ul><li>Start element: name </li></ul><ul><li>Characters: Learning XML </li></ul><ul><li>End element: name </li></ul><ul><li>Start element: author </li></ul><ul><li>Characters: Simon North </li></ul><ul><li>End element: author </li></ul><ul><li>Start element: publication </li></ul><ul><li>Characters: TMH </li></ul><ul><li>End element: publication </li></ul><ul><li>… </li></ul><ul><li>End element: book </li></ul><ul><li>End document </li></ul>
  13. 13. Sample XML Tree
  14. 14. Tree Processing Sequence 1 2 8 3 4 9 10 14 15 5 6 7 11 12 13 16 17
  15. 15. Sequential Traversal: Summary <ul><li>Order </li></ul><ul><ul><li>Top to bottom </li></ul></ul><ul><ul><li>Left to right </li></ul></ul><ul><li>Advantages </li></ul><ul><ul><li>Simple </li></ul></ul><ul><ul><li>Fast </li></ul></ul><ul><ul><li>Requires less amount of memory </li></ul></ul><ul><li>Drawback </li></ul><ul><ul><li>Not possible to look ahead </li></ul></ul>
  16. 16. SAX Concept
  17. 17. JAXP Java API for XML Processing
  18. 18. JAXP Concept Application program written in Java for working with XML Java API for XML Processing (JAXP) JAXP APIs Simple API for XML Processing (SAX) Document Object Model (DOM) Sequential processing Tree-based processing
  19. 19. JAXP <ul><li>Java API for XML Processing </li></ul><ul><li>Standardized by Sun </li></ul><ul><li>Very thin layer on top of SAX or DOM </li></ul><ul><li>Makes application code parser-independent </li></ul><ul><li>Our programs should use JAXP, which in turn, calls parser APIs </li></ul><ul><li>Include package javax.xml.parsers.* </li></ul>
  20. 20. JAXP: API or Abstraction? <ul><li>JAXP is an API, but is called as an abstraction layer </li></ul><ul><ul><li>Does not provide new means of parsing XML </li></ul></ul><ul><ul><li>Does not add to SAX or DOM </li></ul></ul><ul><ul><li>Does not give new functionality to Java or XML handling </li></ul></ul><ul><ul><li>Makes working with SAX and DOM easier </li></ul></ul><ul><ul><li>It is vendor-neutral </li></ul></ul>
  21. 21. JAXP and Parsing <ul><li>JAXP is not a replacement for SAX, DOM, JDOM etc </li></ul><ul><li>Some vendor must supply the implementation of SAX, DOM, etc </li></ul><ul><li>JAXP provides APIs to use these implementations </li></ul><ul><ul><li>In the early versions of JDK, Sun had supplied a parser called Crimson </li></ul></ul><ul><ul><li>Now, Sun provides Apache Xerces </li></ul></ul><ul><ul><li>Both are not a part of JAXP API – they are part of JAXP distribution </li></ul></ul><ul><li>In JDK, we can locate Xerces implementations in the org.xml.sax and org.w3c.dom packages </li></ul>
  22. 22. JAXP API <ul><li>The main JAXP APIs are defined in the package javax.xml.parsers </li></ul><ul><li>Contains two vendor-neutral factory classes </li></ul><ul><ul><li>SAXParserFactory – Gives a SAXParser object </li></ul></ul><ul><ul><li>DocumentBuilderFactory – Gives a DocumentBuilder object </li></ul></ul><ul><ul><ul><li>DocumentBuilder, in turn, gives Document object </li></ul></ul></ul>
  23. 23. Package Details <ul><li>javax.xml.parsers </li></ul><ul><ul><li>The JAXP APIs, which provide 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 Document class (a DOM), as well as classes for all of the components of a DOM. </li></ul></ul><ul><li>org.xml.sax </li></ul><ul><ul><li>Defines the basic SAX APIs. </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>
  24. 24. Which Packages to use in JAXP? <ul><li>We need to include two sets of packages – one for JAXP and the other for SAX/DOM, as appropriate </li></ul><ul><li>// JAXP </li></ul><ul><li>import javax.xml.parsers.SAXParserFactory; </li></ul><ul><li>// SAX </li></ul><ul><li>import org.xml.sax.Attributes; </li></ul><ul><li>import org.xml.sax.SAXException; </li></ul><ul><li>import org.xml.sax.SAXNotRecognizedException; </li></ul><ul><li>import org.xml.sax.SAXNotSupportedException; </li></ul><ul><li>import org.xml.sax.SAXParseException; </li></ul><ul><li>import org.xml.sax.XMLReader; </li></ul><ul><li>import org.xml.sax.helpers.DefaultHandler; </li></ul><ul><li>import org.xml.sax.helpers.XMLReaderFactory; </li></ul>
  25. 25. SAX Programming in JAXP
  26. 26. SAX Approach
  27. 27. Key SAX APIs – 1 <ul><li>SAXParserFactory </li></ul><ul><ul><li>Creates an instance of the parser determined by the system property, javax.xml.parsers.SAXParserFactory. </li></ul></ul><ul><li>  </li></ul><ul><li>SAXParser </li></ul><ul><ul><li>An interface that defines several kinds of parse() methods. In general, you pass an XML data source and a DefaultHandler object to the parser, which processes the XML and invokes the appropriate methods in the handler object. </li></ul></ul><ul><li>  </li></ul><ul><li>  </li></ul>
  28. 28. Key SAX APIs – 2 <ul><li>SAXReader </li></ul><ul><ul><li>The SAXParser wraps a SAXReader. Typically, you don't care about that, but every once in a while you need to get hold of it using SAXParser's getXMLReader(), so you can configure it. It is the SAXReader which carries on the conversation with the SAX event handlers you define. </li></ul></ul><ul><li>DefaultHandler </li></ul><ul><ul><li>Not shown in the diagram, a DefaultHandler implements the ContentHandler, ErrorHandler, DTDHandler, and EntityResolver interfaces (with null methods), so you can override only the ones you're interested in. </li></ul></ul>
  29. 29. 1 – Specify the Parser <ul><li>Various approaches are possible </li></ul><ul><ul><li>Set a system property for javax.xml.parsers.SAXParserfactory </li></ul></ul><ul><ul><li>Specify the parser in jre_dir/lib/jaxp.properties </li></ul></ul><ul><ul><li>Use system-dependent default parser (check documentation) </li></ul></ul><ul><li>Usually done at the time of JDK installation itself automatically </li></ul>
  30. 30. 1 – Specify the Parser <ul><li>Example </li></ul><ul><li>Public static void main (String [] args) </li></ul><ul><li>{ </li></ul><ul><li>String jaxpPropertyName = “javax.xml.parsers.SAXParserFactory”; </li></ul><ul><li>… </li></ul><ul><li>} </li></ul>
  31. 31. 2 – Create a Parser Instance <ul><li>Steps </li></ul><ul><ul><li>Create an instance of a parser factory </li></ul></ul><ul><ul><li>Use that to create a SAXParser object </li></ul></ul><ul><li>Example </li></ul><ul><li>SAXParserFactory factory = SAXParserFactory.newInstance (); </li></ul><ul><li>SaxParser p = factory.newSAXParser (); </li></ul>
  32. 32. 3 – Create an Event Handler <ul><li>Event handler responds to parsing events </li></ul><ul><ul><li>It is a subclass of DefaultHandler </li></ul></ul><ul><ul><ul><li>public class MyHandler extends DefaultHandler { … } </li></ul></ul></ul><ul><ul><li>Main event methods (callbacks) </li></ul></ul><ul><ul><ul><li>startDocument, endDocument </li></ul></ul></ul><ul><ul><ul><li>startElement, endElement </li></ul></ul></ul><ul><ul><ul><li>characters, ignoreableWhitespace </li></ul></ul></ul>
  33. 33. 3 – Create an Event Handler <ul><li>Example method: startElement </li></ul><ul><li>Declaration </li></ul><ul><li>public void startElement (String nameSpaceURI, </li></ul><ul><li> String localName, </li></ul><ul><li> String qualifiedName, </li></ul><ul><li> Attributes attributes) </li></ul><ul><li>throws SASException </li></ul><ul><li>Arguments </li></ul><ul><li>nameSpaceURI URI identifying the namespace uniquely </li></ul><ul><li>localName Element name without namespace prefix </li></ul><ul><li>qualifiedName Complete element name, including namespace prefix </li></ul><ul><li>attributes Attributes object, representing attributes of the element </li></ul>
  34. 34. 3 – Create an Event Handler <ul><li>nameSpaceURI </li></ul><ul><li><cwp:book xmlns:cwp= “http://www.test.com/xml/”> </li></ul><ul><li> qualifiedName attribute[1] </li></ul><ul><li>< cwp:chapter number=“23” part=“Server programming” > </li></ul><ul><li><cwp: title > XML made easy </cwp:title> </li></ul><ul><li></cwp:chapter> </li></ul><ul><li> localName </li></ul><ul><li></cwp:book> </li></ul>
  35. 35. 4 – Invoke the Parser <ul><li>Call the parse method, supplying: </li></ul><ul><ul><li>The content handler </li></ul></ul><ul><ul><li>The XML document </li></ul></ul><ul><ul><ul><li>File or Input stream </li></ul></ul></ul><ul><ul><ul><li>p.parse (file name, handler); </li></ul></ul></ul>
  36. 36. Sample XML File (emp.xml) <ul><li><?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?> </li></ul><ul><li><root> </li></ul><ul><li><employee>test 1</employee> </li></ul><ul><li><employee>test 1</employee> </li></ul><ul><li><employee>test 1</employee> </li></ul><ul><li><employee>test 1</employee> </li></ul><ul><li><employee>test 1</employee> </li></ul><ul><li><employee>test 1</employee> </li></ul><ul><li><employee>test 1</employee> </li></ul><ul><li></root> </li></ul>
  37. 37. Java Program to Count Total Number of Elements <ul><li>import javax.xml.parsers.SAXParser; </li></ul><ul><li>import javax.xml.parsers.SAXParserFactory; </li></ul><ul><li>import org.xml.sax.*; </li></ul><ul><li>import org.xml.sax.helpers.DefaultHandler; </li></ul><ul><li>public class SAXEmployeeCount extends DefaultHandler </li></ul><ul><li>{ </li></ul><ul><li>int tagCount = 0; </li></ul><ul><li>public void startElement (String uri, String localName, String rawName, Attributes attributes) </li></ul><ul><li>{ </li></ul><ul><li>tagCount++; </li></ul><ul><li>} </li></ul><ul><li>public void endDocument() </li></ul><ul><li>{ </li></ul><ul><li>System.out.println(&quot;There are &quot; + tagCount + &quot; elements.&quot;); </li></ul><ul><li>} </li></ul><ul><li>public static void main(String[] args) </li></ul><ul><li>{ </li></ul><ul><li>SAXEmployeeCount handler = new SAXEmployeeCount (); </li></ul><ul><li>try { </li></ul><ul><li>SAXParserFactory spf = SAXParserFactory.newInstance (); </li></ul><ul><li>SAXParser parser = spf.newSAXParser (); </li></ul><ul><li>parser.parse(&quot;employee.xml&quot;, handler); </li></ul><ul><li>} </li></ul><ul><li>catch (Exception ex) { </li></ul><ul><li>System.out.println(ex); </li></ul><ul><li>} </li></ul><ul><li>} </li></ul><ul><li>} </li></ul>
  38. 38. Count Only Book Elements <ul><li><?xml version=&quot;1.0&quot;?> </li></ul><ul><li><books> </li></ul><ul><li><book category=&quot;reference&quot;> </li></ul><ul><li><author>Nigel Rees</author> </li></ul><ul><li><title>Sayings of the Century</title> </li></ul><ul><li><price>8.95</price> </li></ul><ul><li></book> </li></ul><ul><li><book category=&quot;fiction&quot;> </li></ul><ul><li><author>Evelyn Waugh</author> </li></ul><ul><li><title>Sword of Honour</title> </li></ul><ul><li><price>12.99</price> </li></ul><ul><li></book> </li></ul><ul><li><book category=&quot;fiction&quot;> </li></ul><ul><li><author>Herman Melville</author> </li></ul><ul><li><title>Moby Rick</title> </li></ul><ul><li><price>8.99</price> </li></ul><ul><li></book> </li></ul><ul><li></books> </li></ul>
  39. 39. Parsing Code in JAXP <ul><li>import java.io.IOException; </li></ul><ul><li>import java.lang.*; </li></ul><ul><li>import javax.xml.parsers.SAXParser; </li></ul><ul><li>import javax.xml.parsers.SAXParserFactory; </li></ul><ul><li>import org.xml.sax.Attributes; </li></ul><ul><li>import org.xml.sax.Locator; </li></ul><ul><li>import org.xml.sax.SAXException; </li></ul><ul><li>import org.xml.sax.SAXNotRecognizedException; </li></ul><ul><li>import org.xml.sax.SAXNotSupportedException; </li></ul><ul><li>import org.xml.sax.SAXParseException; </li></ul><ul><li>import org.xml.sax.XMLReader; </li></ul><ul><li>import org.xml.sax.ext.LexicalHandler; </li></ul><ul><li>import org.xml.sax.helpers.DefaultHandler; </li></ul><ul><li>import org.xml.sax.helpers.ParserAdapter; </li></ul><ul><li>import org.xml.sax.helpers.XMLReaderFactory; </li></ul><ul><li>public class BookCount extends DefaultHandler{ </li></ul><ul><li>private int count = 0; </li></ul><ul><li>public void startDocument() throws SAXException { </li></ul><ul><li>System.out.println(&quot;Start document ...&quot;); </li></ul><ul><li>} </li></ul><ul><li>public void startElement(String uri, String local, String raw, </li></ul><ul><li>Attributes attrs) throws SAXException { </li></ul><ul><li>int year = 0; </li></ul><ul><li>String attrValue; </li></ul><ul><li>System.out.println (&quot;Current element = &quot; + raw); </li></ul><ul><li>if (raw.equals (&quot;book&quot;)) { </li></ul><ul><li>count++; </li></ul><ul><li>} </li></ul><ul><li>} </li></ul><ul><li>public void endDocument() throws SAXException { </li></ul><ul><li>System.out.println(&quot;The total number of books = &quot; + count); </li></ul><ul><li>} </li></ul><ul><li>public static void main (String[] args) throws Exception { </li></ul><ul><li>BookCount handler = new BookCount (); </li></ul><ul><li>try { </li></ul><ul><li>SAXParserFactory spf = SAXParserFactory.newInstance (); </li></ul><ul><li>SAXParser parser = spf.newSAXParser (); </li></ul><ul><li>parser.parse (&quot;book.xml&quot;, handler); </li></ul><ul><li>} </li></ul><ul><li>catch (SAXException e) { </li></ul><ul><li>System.err.println(e.getMessage()); </li></ul><ul><li>} </li></ul><ul><li>} </li></ul><ul><li>} </li></ul>
  40. 40. Specifying Parser Name <ul><li>import java.io.IOException; </li></ul><ul><li>import javax.xml.parsers.SAXParser; </li></ul><ul><li>import javax.xml.parsers.SAXParserFactory; </li></ul><ul><li>import org.xml.sax.Attributes; </li></ul><ul><li>import org.xml.sax.Locator; </li></ul><ul><li>import org.xml.sax.SAXException; </li></ul><ul><li>import org.xml.sax.SAXNotRecognizedException; </li></ul><ul><li>import org.xml.sax.SAXNotSupportedException; </li></ul><ul><li>import org.xml.sax.SAXParseException; </li></ul><ul><li>import org.xml.sax.XMLReader; </li></ul><ul><li>import org.xml.sax.ext.LexicalHandler; </li></ul><ul><li>import org.xml.sax.helpers.DefaultHandler; </li></ul><ul><li>import org.xml.sax.helpers.ParserAdapter; </li></ul><ul><li>import org.xml.sax.helpers.XMLReaderFactory; </li></ul><ul><li>public class SAXApp extends DefaultHandler{ </li></ul><ul><li>// default parser to use </li></ul><ul><li>protected static final String DEFAULT_PARSER_NAME = &quot;org.apache.xerces.parsers.SAXParser&quot;; </li></ul><ul><li>private int count = 0; </li></ul><ul><li>public void countTopics () throws IOException, SAXException { </li></ul><ul><li>// create parser </li></ul><ul><li>try { </li></ul><ul><li>System.out.println (&quot;Inside countTopics&quot;); </li></ul><ul><li>} </li></ul><ul><li>catch (Exception e) { </li></ul><ul><li>e.printStackTrace(System.err); </li></ul><ul><li>} </li></ul><ul><li>} </li></ul><ul><li>public void startElement(String uri, String local, String raw, </li></ul><ul><li>Attributes attrs) throws SAXException { </li></ul><ul><li>if (raw.equals(&quot;topic&quot;)) count++; </li></ul><ul><li>System.out.println (raw); </li></ul><ul><li>} </li></ul><ul><li>public void endDocument() throws SAXException { </li></ul><ul><li>System.out.println(&quot;There are &quot; + count + &quot; topics&quot;); </li></ul><ul><li>} </li></ul><ul><li>public static void main (String[] args) throws Exception{ </li></ul><ul><li>System.out.println (&quot;Inside main ...&quot;); </li></ul><ul><li>SAXApp handler = new SAXApp(); </li></ul><ul><li>try { </li></ul><ul><li>SAXParserFactory spf = SAXParserFactory.newInstance (); </li></ul><ul><li>SAXParser parser = spf.newSAXParser (); </li></ul><ul><li>parser.parse (&quot;contents.xml&quot;, handler); </li></ul><ul><li>} </li></ul><ul><li>catch (SAXException e) { </li></ul><ul><li>System.err.println(e.getMessage()); </li></ul><ul><li>} </li></ul><ul><li>} </li></ul><ul><li>} </li></ul>
  41. 41. Exercise <ul><li>Consider the following XML file and write a program to count the number of elements that have at least one attribute. </li></ul><ul><li><?xml version=&quot;1.0&quot;?> </li></ul><ul><li><BOOKS> </li></ul><ul><li><BOOK pubyear=&quot;1929&quot;> </li></ul><ul><li><BOOK_TITLE>Look Homeward, Angel</BOOK_TITLE> </li></ul><ul><li><AUTHOR>Wolfe, Thomas</AUTHOR> </li></ul><ul><li></BOOK> </li></ul><ul><li><BOOK pubyear=&quot;1973&quot;> </li></ul><ul><li><BOOK_TITLE>Gravity's Rainbow</BOOK_TITLE> </li></ul><ul><li><AUTHOR>Pynchon, Thomas</AUTHOR> </li></ul><ul><li></BOOK> </li></ul><ul><li><BOOK pubyear=&quot;1977&quot;> </li></ul><ul><li><BOOK_TITLE>Cards as Weapons</BOOK_TITLE> </li></ul><ul><li><AUTHOR>Jay, Ricky</AUTHOR> </li></ul><ul><li></BOOK> </li></ul><ul><li><BOOK pubyear=&quot;2001&quot;> </li></ul><ul><li><BOOK_TITLE>Computer Networks</BOOK_TITLE> </li></ul><ul><li><AUTHOR>Tanenbaum, Andrew</AUTHOR> </li></ul><ul><li></BOOK> </li></ul><ul><li></BOOKS> </li></ul>
  42. 42. Solution <ul><li>import java.io.IOException; </li></ul><ul><li>import javax.xml.parsers.SAXParser; </li></ul><ul><li>import javax.xml.parsers.SAXParserFactory; </li></ul><ul><li>import org.xml.sax.Attributes; </li></ul><ul><li>import org.xml.sax.Locator; </li></ul><ul><li>import org.xml.sax.SAXException; </li></ul><ul><li>import org.xml.sax.SAXNotRecognizedException; </li></ul><ul><li>import org.xml.sax.SAXNotSupportedException; </li></ul><ul><li>import org.xml.sax.SAXParseException; </li></ul><ul><li>import org.xml.sax.XMLReader; </li></ul><ul><li>import org.xml.sax.ext.LexicalHandler; </li></ul><ul><li>import org.xml.sax.helpers.DefaultHandler; </li></ul><ul><li>import org.xml.sax.helpers.ParserAdapter; </li></ul><ul><li>import org.xml.sax.helpers.XMLReaderFactory; </li></ul><ul><li>public class countAttr extends DefaultHandler{ </li></ul><ul><li>private int count = 0; </li></ul><ul><li>public void startDocument() throws SAXException { </li></ul><ul><li>System.out.println(&quot;Start document ...&quot;); </li></ul><ul><li>} </li></ul><ul><li>public void startElement(String uri, String local, String raw, </li></ul><ul><li>Attributes attrs) throws SAXException { </li></ul><ul><li>System.out.println (&quot;Current element = &quot; + raw); </li></ul><ul><li>if (attrs.getLength () != 0) { </li></ul><ul><li>count++; </li></ul><ul><li>} </li></ul><ul><li>} </li></ul><ul><li>public void endDocument() throws SAXException { </li></ul><ul><li>System.out.println(&quot;The total number of attributes = &quot; + count); </li></ul><ul><li>} </li></ul><ul><li>public static void main (String[] args) throws Exception { </li></ul><ul><li>countAttr handler = new countAttr (); </li></ul><ul><li>try { </li></ul><ul><li>SAXParserFactory spf = SAXParserFactory.newInstance (); </li></ul><ul><li>SAXParser parser = spf.newSAXParser (); </li></ul><ul><li>parser.parse (&quot;countAttr.xml&quot;, handler); </li></ul><ul><li>} </li></ul><ul><li>catch (SAXException e) { </li></ul><ul><li>System.err.println(e.getMessage()); </li></ul><ul><li>} </li></ul><ul><li>} </li></ul><ul><li>} </li></ul>
  43. 43. Exercise <ul><li>For the same XML file, display element names only if the book is published in the 1970s. </li></ul>
  44. 44. Solution <ul><li>import java.io.IOException; </li></ul><ul><li>import java.lang.*; </li></ul><ul><li>import javax.xml.parsers.SAXParser; </li></ul><ul><li>import javax.xml.parsers.SAXParserFactory; </li></ul><ul><li>import org.xml.sax.Attributes; </li></ul><ul><li>import org.xml.sax.Locator; </li></ul><ul><li>import org.xml.sax.SAXException; </li></ul><ul><li>import org.xml.sax.SAXNotRecognizedException; </li></ul><ul><li>import org.xml.sax.SAXNotSupportedException; </li></ul><ul><li>import org.xml.sax.SAXParseException; </li></ul><ul><li>import org.xml.sax.XMLReader; </li></ul><ul><li>import org.xml.sax.ext.LexicalHandler; </li></ul><ul><li>import org.xml.sax.helpers.DefaultHandler; </li></ul><ul><li>import org.xml.sax.helpers.ParserAdapter; </li></ul><ul><li>import org.xml.sax.helpers.XMLReaderFactory; </li></ul><ul><li>public class seventiesBooks extends DefaultHandler{ </li></ul><ul><li>private int count = 0; </li></ul><ul><li>public void startDocument() throws SAXException { </li></ul><ul><li>System.out.println(&quot;Start document ...&quot;); </li></ul><ul><li>} </li></ul><ul><li>public void startElement(String uri, String local, String raw, </li></ul><ul><li>Attributes attrs) throws SAXException { </li></ul><ul><li>int year = 0; </li></ul><ul><li>String attrValue; </li></ul><ul><li>System.out.println (&quot;Current element = &quot; + raw); </li></ul><ul><li>if (attrs.getLength () > 0) { </li></ul><ul><li>attrValue = attrs.getValue (0); </li></ul><ul><li>year = Integer.parseInt (attrValue); </li></ul><ul><li>if (year < 1970) { </li></ul><ul><li>count++; </li></ul><ul><li>} </li></ul><ul><li>} </li></ul><ul><li>} </li></ul><ul><li>public void endDocument() throws SAXException { </li></ul><ul><li>System.out.println(&quot;The total number of matching elements = &quot; + count); </li></ul><ul><li>} </li></ul><ul><li>public static void main (String[] args) throws Exception { </li></ul><ul><li>seventiesBooks handler = new seventiesBooks(); </li></ul><ul><li>try { </li></ul><ul><li>SAXParserFactory spf = SAXParserFactory.newInstance (); </li></ul><ul><li>SAXParser parser = spf.newSAXParser (); </li></ul><ul><li>parser.parse (&quot;countAttr.xml&quot;, handler); </li></ul><ul><li>} </li></ul><ul><li>catch (SAXException e) { </li></ul><ul><li>System.err.println(e.getMessage()); </li></ul><ul><li>} </li></ul><ul><li>} </li></ul><ul><li>} </li></ul>
  45. 45. Exercise <ul><li>Consider the following XML document (stock.xml) </li></ul><ul><li><?xml version=&quot;1.0&quot;?> </li></ul><ul><li><stock> </li></ul><ul><li><stockinfo symbol=&quot;IFL&quot;> </li></ul><ul><li><company>i-flex solutions limited</company> </li></ul><ul><li><price>2500</price> </li></ul><ul><li></stockinfo> </li></ul><ul><li><stockinfo symbol=&quot;HLL&quot;> </li></ul><ul><li><company>Hindustan Lever</company> </li></ul><ul><li><price>1840</price> </li></ul><ul><li></stockinfo> </li></ul><ul><li><stockinfo symbol=&quot;LT&quot;> </li></ul><ul><li><company>Laresn and Toubro</company> </li></ul><ul><li><price>2678</price> </li></ul><ul><li></stockinfo> </li></ul><ul><li><stockinfo symbol=&quot;Rel&quot;> </li></ul><ul><li><company>Reliance Communications</company> </li></ul><ul><li><price>1743</price> </li></ul><ul><li></stockinfo> </li></ul><ul><li></stock> </li></ul><ul><li>Produce output as shown on the next slide </li></ul>
  46. 46. Expected Output
  47. 47. Solution <ul><li>import java.io.*; </li></ul><ul><li>import org.xml.sax.*; </li></ul><ul><li>import org.xml.sax.helpers.*; </li></ul><ul><li>import javax.xml.parsers.*; </li></ul><ul><li>public class DisplayStockDetails extends DefaultHandler { </li></ul><ul><li>public void startDocument () throws SAXException { </li></ul><ul><li>System.out.println (&quot;nDisplaying Stock Details&quot;); </li></ul><ul><li>System.out.println (&quot;=========================n&quot;); </li></ul><ul><li>} </li></ul><ul><li>public void endDocument () throws SAXException { </li></ul><ul><li>System.out.println (&quot;nEnd of Details&quot;); </li></ul><ul><li>System.out.println (&quot;==============n&quot;); </li></ul><ul><li>} </li></ul><ul><li>public void startElement (String uri, String local, String raw, </li></ul><ul><li>Attributes attrs) throws SAXException { </li></ul><ul><li>// Skip processing root element </li></ul><ul><li>if (local.equals (&quot;stock&quot;)) </li></ul><ul><li>return; </li></ul><ul><li>// Skip processing if there are no attributes </li></ul><ul><li>if (attrs == null) </li></ul><ul><li>return; </li></ul><ul><li>for (int i=0; i<attrs.getLength (); i++) { </li></ul><ul><li>System.out.println (&quot;[Symbol: &quot; + attrs.getValue (i) + &quot;]&quot;); </li></ul><ul><li>} </li></ul><ul><li>} </li></ul><ul><li>public void endElement (String uri, String local, String raw) throws SAXException { </li></ul><ul><li>// System.out.println (); </li></ul><ul><li>} </li></ul><ul><li>public void characters (char[] ch, int start, int length) throws SAXException { </li></ul><ul><li>System.out.println (new String (ch, start, length)); </li></ul><ul><li>} </li></ul><ul><li>public static void main (String[] args) throws Exception { </li></ul><ul><li>DisplayStockDetails handler = new DisplayStockDetails (); </li></ul><ul><li>try { </li></ul><ul><li>SAXParserFactory spf = SAXParserFactory.newInstance (); </li></ul><ul><li>SAXParser parser = spf.newSAXParser (); </li></ul><ul><li>parser.parse (&quot;stock.xml&quot;, handler); </li></ul><ul><li>} </li></ul><ul><li>catch (SAXException e) { </li></ul><ul><li>System.err.println(e.getMessage()); </li></ul><ul><li>} </li></ul><ul><li>} </li></ul><ul><li>} </li></ul>
  48. 48. Exercise <ul><li>Consider the following XML document. Write a Java program to find out the maximum price, and also display the author name corresponding to that book. </li></ul><ul><li><?xml version=&quot;1.0&quot;?> </li></ul><ul><li><books> </li></ul><ul><li><book category=&quot;reference&quot;> </li></ul><ul><li><author>Nigel Rees</author> </li></ul><ul><li><title>Sayings of the Century</title> </li></ul><ul><li><price>8</price> </li></ul><ul><li></book> </li></ul><ul><li><book category=&quot;fiction&quot;> </li></ul><ul><li><author>Evelyn Waugh</author> </li></ul><ul><li><title>Sword of Honour</title> </li></ul><ul><li><price>12</price> </li></ul><ul><li></book> </li></ul><ul><li><book category=&quot;fiction&quot;> </li></ul><ul><li><author>Herman Melville</author> </li></ul><ul><li><title>Moby Rick</title> </li></ul><ul><li><price>8</price> </li></ul><ul><li></book> </li></ul><ul><li><book category=&quot;non-fiction&quot;> </li></ul><ul><li><author>Bill Bryson</author> </li></ul><ul><li><title>A Short History Of Everything</title> </li></ul><ul><li><price>20</price> </li></ul><ul><li></book> </li></ul><ul><li><book category=&quot;reference&quot;> </li></ul><ul><li><author>Herb Schildt</author> </li></ul><ul><li><title>Java - The Complete Reference</title> </li></ul><ul><li><price>23</price> </li></ul><ul><li></book> </li></ul><ul><li><book category=&quot;non-fiction&quot;> </li></ul><ul><li><author>Paul Smith</author> </li></ul><ul><li><title>The Scientists</title> </li></ul><ul><li><price>12</price> </li></ul><ul><li></book> </li></ul><ul><li></books> </li></ul>
  49. 49. Solution <ul><li>package saxexamples; </li></ul><ul><li>import javax.xml.parsers.SAXParser; </li></ul><ul><li>import javax.xml.parsers.SAXParserFactory; </li></ul><ul><li>import org.xml.sax.Attributes; </li></ul><ul><li>import org.xml.sax.SAXException; </li></ul><ul><li>import org.xml.sax.helpers.DefaultHandler; </li></ul><ul><li>public class HighestPricedBook extends DefaultHandler { </li></ul><ul><li>private int maxPriceBookPrice = 0; </li></ul><ul><li>private String currentBookAuthor, maxPriceBookAuthor; </li></ul><ul><li>private boolean flagIsCurrentElementPrice = false, flagIsCurrentElementAuthor = false; </li></ul><ul><li>public void startDocument() throws SAXException { </li></ul><ul><li>System.out.println(&quot;Start document ...&quot;); </li></ul><ul><li>} </li></ul><ul><li>public void startElement(String uri, String local, String raw, </li></ul><ul><li>Attributes attrs) throws SAXException { </li></ul><ul><li>System.out.println(&quot;Current element = &quot; + raw); </li></ul><ul><li>if (raw.equals(&quot;author&quot;)) { </li></ul><ul><li>flagIsCurrentElementAuthor = true; </li></ul><ul><li>System.out.println (&quot;Current element is book&quot;); </li></ul><ul><li>} else if (raw.equals(&quot;price&quot;)) { </li></ul><ul><li>flagIsCurrentElementPrice = true; </li></ul><ul><li>} </li></ul><ul><li>} </li></ul><ul><li>public void characters(char[] ch, int start, int len) throws SAXException { </li></ul><ul><li>if (flagIsCurrentElementAuthor == true) { </li></ul><ul><li>flagIsCurrentElementAuthor = false; </li></ul><ul><li>System.out.println(&quot;ch = &quot; + ch); </li></ul><ul><li>System.out.println(&quot;start = &quot; + start); </li></ul><ul><li>System.out.println(&quot;len = &quot; + len); </li></ul><ul><li>StringBuffer buffer = new StringBuffer(); </li></ul><ul><li>for (int i = 0; i < len; i++) { </li></ul><ul><li>buffer.append(ch[start + i]); </li></ul><ul><li>} </li></ul><ul><li>System.out.println(&quot;*** buffer = &quot; + buffer + &quot; ***&quot;); </li></ul><ul><li>currentBookAuthor = buffer.toString(); </li></ul><ul><li>System.out.println(&quot;*** str = &quot; + currentBookAuthor + &quot; ***&quot;); </li></ul><ul><li>} </li></ul><ul><li>else if (flagIsCurrentElementPrice == true) { </li></ul><ul><li>flagIsCurrentElementPrice = false; </li></ul><ul><li>System.out.println(&quot;ch = &quot; + ch); </li></ul><ul><li>System.out.println(&quot;start = &quot; + start); </li></ul><ul><li>System.out.println(&quot;len = &quot; + len); </li></ul><ul><li>StringBuffer buffer = new StringBuffer(); </li></ul><ul><li>for (int i = 0; i < len; i++) { </li></ul><ul><li>buffer.append(ch[start + i]); </li></ul><ul><li>} </li></ul><ul><li>System.out.println(&quot;*** buffer = &quot; + buffer + &quot; ***&quot;); </li></ul><ul><li>String str = buffer.substring(0); </li></ul><ul><li>int uprice = Integer.parseInt(str); </li></ul><ul><li>if (uprice > maxPriceBookPrice) { </li></ul><ul><li>maxPriceBookPrice = uprice; </li></ul><ul><li>maxPriceBookAuthor = currentBookAuthor; </li></ul><ul><li>} </li></ul><ul><li>System.out.println(&quot;Current maximum price = &quot; + maxPriceBookPrice); </li></ul><ul><li>} </li></ul><ul><li>} </li></ul><ul><li>public void endDocument() throws SAXException { </li></ul><ul><li>System.out.println(&quot;The book author with the maximum price = &quot; + maxPriceBookAuthor); </li></ul><ul><li>System.out.println(&quot;And the book price = &quot; + maxPriceBookPrice); </li></ul><ul><li>} </li></ul><ul><li>public static void main(String[] args) throws Exception { </li></ul><ul><li>HighestPricedBook handler = new HighestPricedBook(); </li></ul><ul><li>try { </li></ul><ul><li>SAXParserFactory spf = SAXParserFactory.newInstance(); </li></ul><ul><li>SAXParser parser = spf.newSAXParser(); </li></ul><ul><li>parser.parse(&quot;book.xml&quot;, handler); </li></ul><ul><li>} catch (SAXException e) { </li></ul><ul><li>System.err.println(e.getMessage()); </li></ul><ul><li>} </li></ul><ul><li>} </li></ul><ul><li>} </li></ul>
  50. 50. Exercise <ul><li>Consider the following XML file and write a program to find out and display the total cost for all CDs. </li></ul><ul><li><?xml version=&quot;1.0&quot; encoding=&quot;ISO-8859-1&quot;?> </li></ul><ul><li><catalog> </li></ul><ul><li><cd> </li></ul><ul><li><title>Empire Burlesque</title> </li></ul><ul><li><artist>Bob Dylan</artist> </li></ul><ul><li><country>USA</country> </li></ul><ul><li><company>Columbia</company> </li></ul><ul><li><price>10.90</price> </li></ul><ul><li><year>1985</year> </li></ul><ul><li></cd> </li></ul><ul><li><cd> </li></ul><ul><li><title>Candle in the wind</title> </li></ul><ul><li><artist>Elton John</artist> </li></ul><ul><li><country>UK</country> </li></ul><ul><li><company>HMV</company> </li></ul><ul><li><price>8.20</price> </li></ul><ul><li><year>1998</year> </li></ul><ul><li></cd> </li></ul><ul><li></catalog> </li></ul>
  51. 51. Solution <ul><li>import java.io.IOException; </li></ul><ul><li>import java.lang.*; </li></ul><ul><li>import javax.xml.parsers.SAXParser; </li></ul><ul><li>import javax.xml.parsers.SAXParserFactory; </li></ul><ul><li>import org.xml.sax.Attributes; </li></ul><ul><li>import org.xml.sax.Locator; </li></ul><ul><li>import org.xml.sax.SAXException; </li></ul><ul><li>import org.xml.sax.SAXNotRecognizedException; </li></ul><ul><li>import org.xml.sax.SAXNotSupportedException; </li></ul><ul><li>import org.xml.sax.SAXParseException; </li></ul><ul><li>import org.xml.sax.XMLReader; </li></ul><ul><li>import org.xml.sax.ext.LexicalHandler; </li></ul><ul><li>import org.xml.sax.helpers.DefaultHandler; </li></ul><ul><li>import org.xml.sax.helpers.ParserAdapter; </li></ul><ul><li>import org.xml.sax.helpers.XMLReaderFactory; </li></ul><ul><li>public class CDPrice extends DefaultHandler{ </li></ul><ul><li>private int count = 0, total = 0; </li></ul><ul><li>private boolean flagIsAvailable = false, flagIsCurrentElementPrice = false; </li></ul><ul><li>public void startDocument() throws SAXException { </li></ul><ul><li>System.out.println(&quot;Start document ...&quot;); </li></ul><ul><li>} </li></ul><ul><li>public void startElement(String uri, String local, String raw, </li></ul><ul><li>Attributes attrs) throws SAXException { </li></ul><ul><li>int year = 0; </li></ul><ul><li>String attrValue; </li></ul><ul><li>System.out.println (&quot;Current element = &quot; + raw); </li></ul><ul><li>if (raw.equals (&quot;price&quot;)) { </li></ul><ul><li>flagIsCurrentElementPrice = true; </li></ul><ul><li>System.out.println (&quot;INSIDE if of startElement ===&quot;); </li></ul><ul><li>} </li></ul><ul><li>} </li></ul><ul><li>public void characters (char [] ch, int start, int len) throws SAXException { </li></ul><ul><li>if (flagIsCurrentElementPrice) { </li></ul><ul><li> System.out.println (&quot;ch = &quot; + ch); </li></ul><ul><li> System.out.println (&quot;start = &quot; + start); </li></ul><ul><li> System.out.println (&quot;len = &quot; + len); </li></ul><ul><li> StringBuffer buffer = new StringBuffer (); </li></ul><ul><li> for (int i=0; i<len; i++) { </li></ul><ul><li> buffer.append (ch[start+i]); </li></ul><ul><li> } </li></ul><ul><li> System.out.println (&quot;*** buffer = &quot; + buffer + &quot; ***&quot;); </li></ul><ul><li>String str = buffer.substring (0); </li></ul><ul><li> int uprice = Integer.parseInt(str); </li></ul><ul><li> total += uprice; </li></ul><ul><li> flagIsCurrentElementPrice = false; </li></ul><ul><li> System.out.println (&quot;Current total = &quot; + total); </li></ul><ul><li>} </li></ul><ul><li>} </li></ul><ul><li>public void endDocument() throws SAXException { </li></ul><ul><li>System.out.println(&quot;The total price of available CDs = &quot; + total); </li></ul><ul><li>} </li></ul><ul><li>public static void main (String[] args) throws Exception { </li></ul><ul><li>CDPrice handler = new CDPrice(); </li></ul><ul><li>try { </li></ul><ul><li>SAXParserFactory spf = SAXParserFactory.newInstance (); </li></ul><ul><li>SAXParser parser = spf.newSAXParser (); </li></ul><ul><li>parser.parse (&quot;cdcatalog2.xml&quot;, handler); </li></ul><ul><li>} </li></ul><ul><li>catch (SAXException e) { </li></ul><ul><li>System.err.println(e.getMessage()); </li></ul><ul><li>} </li></ul><ul><li>} </li></ul><ul><li>} </li></ul>
  52. 52. Document Object Model (DOM)
  53. 53. DOM – Basic Flow
  54. 54. Basic Concepts
  55. 55. JAXP and DOM – Overview <ul><li>Class DocumentBuilderFactory </li></ul><ul><ul><li>public abstract class javax.xml.parsers.DocumentBuilderFactory extends java.lang.object </li></ul></ul><ul><ul><li>Defines a factory API that enables applications to obtain a parser that produces DOM object trees from XML documents </li></ul></ul><ul><ul><ul><li>parse method: Parses the contents of an XML document and returns the contents as a new Document object </li></ul></ul></ul>
  56. 56. JAXP and DOM – Overview <ul><li>Class DocumentBuilder </li></ul><ul><ul><li>public abstract class javax.xml.parsers. DocumentBuilder extends java.lang.Object </li></ul></ul><ul><ul><li>Defines the API to obtain DOM Document instances from an XML document </li></ul></ul>
  57. 57. JAXP and DOM – Overview <ul><li>Interface Document </li></ul><ul><ul><li>public interface Document extends Node </li></ul></ul><ul><ul><li>The Document interface represents the entire HTML or XML document </li></ul></ul><ul><ul><li>Conceptually, it is the root of the document tree, and provides the primary access to the document's data </li></ul></ul>
  58. 58. JAXP and DOM – Overview <ul><li>Interface Element </li></ul><ul><ul><li>public interface Element extends Node </li></ul></ul><ul><ul><li>The Element interface represents an element in an HTML or XML document </li></ul></ul><ul><ul><li>Elements may have attributes associated with them </li></ul></ul><ul><ul><li>Inherits from Node, the generic Node interface </li></ul></ul><ul><ul><li>attributes may be used to retrieve the set of all attributes for an element </li></ul></ul>
  59. 59. JAXP and DOM <ul><li>DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance (); </li></ul><ul><li>DocumentBuilder builder = factory.newDocumentBuilder (); </li></ul><ul><li>Document document = builder.parse (fileName); </li></ul><ul><li>Element root = document.getDocumentElement (); </li></ul>
  60. 60. Example – XML File <ul><li>Count the number of Employee elements from this XML using DOM </li></ul><ul><li><?xml version=&quot;1.0&quot;?> </li></ul><ul><li><BOOKS xmlns:xsi=&quot;http://www.w3.org/2001/XMLSchema-instance&quot; </li></ul><ul><li>xsi:noNamespaceSchemaLocation=&quot;book.xsd&quot;> </li></ul><ul><li><BOOK> </li></ul><ul><li><TITLE>Computer Networks</TITLE> </li></ul><ul><li><AUTHOR>Andrew Tanenbaum</AUTHOR> </li></ul><ul><li><PUBLISHER>Pearson Education</PUBLISHER> </li></ul><ul><li><PRICE>400</PRICE> </li></ul><ul><li><CATEGORY>Computer Science</CATEGORY> </li></ul><ul><li></BOOK> </li></ul><ul><li><BOOK> </li></ul><ul><li><TITLE>TCP/IP</TITLE> </li></ul><ul><li><AUTHOR>Douglas Comer</AUTHOR> </li></ul><ul><li><PUBLISHER>Pearson Education</PUBLISHER> </li></ul><ul><li><PRICE>350</PRICE> </li></ul><ul><li><CATEGORY>Computer Science</CATEGORY> </li></ul><ul><li></BOOK> </li></ul><ul><li></BOOKS> </li></ul>
  61. 61. Example – Java Code <ul><li>/* </li></ul><ul><li>* To change this template, choose Tools | Templates </li></ul><ul><li>* and open the template in the editor. </li></ul><ul><li>*/ </li></ul><ul><li>package domexamples; </li></ul><ul><li>import org.w3c.dom.*; </li></ul><ul><li>import org.w3c.dom.bootstrap.*; </li></ul><ul><li>import org.w3c.dom.ls.*; </li></ul><ul><li>public class DOMCountExample { </li></ul><ul><li>public static void main(String[] args) { </li></ul><ul><li>try { </li></ul><ul><li>DOMImplementationRegistry registry = DOMImplementationRegistry.newInstance(); </li></ul><ul><li>DOMImplementation domImpl = registry.getDOMImplementation(&quot;LS 3.0&quot;); </li></ul><ul><li>// Casting </li></ul><ul><li>DOMImplementationLS implLS = (DOMImplementationLS) domImpl; </li></ul><ul><li>LSParser parser = implLS.createLSParser(DOMImplementationLS.MODE_SYNCHRONOUS, </li></ul><ul><li>&quot;http://www.w3.org/2001/XMLSchema&quot;); </li></ul><ul><li>DOMConfiguration config = parser.getDomConfig(); </li></ul><ul><li>// Set error handler </li></ul><ul><li>DOMErrorHandlerImpl errorHandler = new DOMErrorHandlerImpl(); </li></ul><ul><li>config.setParameter(&quot;error-handler&quot;, errorHandler); </li></ul><ul><li>// Set schema validation parameters </li></ul><ul><li>config.setParameter(&quot;validate&quot;, Boolean.TRUE); </li></ul><ul><li>config.setParameter(&quot;schema-type&quot;, &quot;http://www.w3.org/2001/XML/Schema&quot;); </li></ul><ul><li>config.setParameter(&quot;validate-if-schema&quot;, Boolean.TRUE); </li></ul><ul><li>config.setParameter(&quot;schema-location&quot;, &quot;book.xsd&quot;); </li></ul><ul><li>Document document = parser.parseURI(&quot;book.xml&quot;); </li></ul><ul><li>Element root = document.getDocumentElement(); </li></ul><ul><li>NodeList nodes = document.getElementsByTagName(&quot;BOOK&quot;); </li></ul><ul><li>System.out.println(&quot;There are &quot; + nodes.getLength() + &quot; elements.&quot;); </li></ul><ul><li>} catch (Exception ex) { </li></ul><ul><li>System.out.println(ex); </li></ul><ul><li>} </li></ul><ul><li>} </li></ul><ul><li>} </li></ul>
  62. 62. Case Study – XML File <ul><li><?xml version=&quot;1.0&quot;?> </li></ul><ul><li><catalog> </li></ul><ul><li><cd> </li></ul><ul><li><title>Empire Burlesque</title> </li></ul><ul><li><artist>Bob Dylan</artist> </li></ul><ul><li><country>USA</country> </li></ul><ul><li><company>Columbia</company> </li></ul><ul><li><price>10</price> </li></ul><ul><li><year>1985</year> </li></ul><ul><li></cd> </li></ul><ul><li><cd> </li></ul><ul><li><title>Candle in the wind</title> </li></ul><ul><li><artist>Elton John</artist> </li></ul><ul><li><country>UK</country> </li></ul><ul><li><company>HMV</company> </li></ul><ul><li><price>8</price> </li></ul><ul><li><year>1998</year> </li></ul><ul><li></cd> </li></ul><ul><li></catalog> </li></ul>
  63. 63. Problem <ul><li>Write a program to find out if an element by the name price exists in the XML file and display its contents </li></ul>
  64. 64. Solution <ul><li>package domexamples; </li></ul><ul><li>import org.w3c.dom.*; </li></ul><ul><li>import org.w3c.dom.bootstrap.*; </li></ul><ul><li>import org.w3c.dom.ls.*; </li></ul><ul><li>public class CountPriceElements { </li></ul><ul><li>public static void main (String[] args) { </li></ul><ul><li>NodeList elements; </li></ul><ul><li>String elementName = &quot;price&quot;; </li></ul><ul><li>try { </li></ul><ul><li>DOMImplementationRegistry registry = DOMImplementationRegistry.newInstance(); </li></ul><ul><li>DOMImplementation domImpl = registry.getDOMImplementation(&quot;LS 3.0&quot;); </li></ul><ul><li>// Casting </li></ul><ul><li>DOMImplementationLS implLS = (DOMImplementationLS) domImpl; </li></ul><ul><li>LSParser parser = implLS.createLSParser(DOMImplementationLS.MODE_SYNCHRONOUS, </li></ul><ul><li>&quot;http://www.w3.org/2001/XMLSchema&quot;); </li></ul><ul><li>DOMConfiguration config = parser.getDomConfig(); </li></ul><ul><li>// Set error handler </li></ul><ul><li>DOMErrorHandlerImpl errorHandler = new DOMErrorHandlerImpl(); </li></ul><ul><li>config.setParameter(&quot;error-handler&quot;, errorHandler); </li></ul><ul><li>// Set schema validation parameters </li></ul><ul><li>// config.setParameter(&quot;validate&quot;, Boolean.TRUE); </li></ul><ul><li>// config.setParameter(&quot;schema-type&quot;, &quot;http://www.w3.org/2001/XML/Schema&quot;); </li></ul><ul><li>// config.setParameter(&quot;validate-if-schema&quot;, Boolean.TRUE); </li></ul><ul><li>// config.setParameter(&quot;schema-location&quot;, &quot;book.xsd&quot;); </li></ul><ul><li>Document document = parser.parseURI(&quot;CDCatalog.xml&quot;); </li></ul><ul><li>Element root = document.getDocumentElement(); </li></ul><ul><li>System.out.println (&quot;In main ... XML file openend successfully ...&quot;); </li></ul><ul><li>elements = document.getElementsByTagName(elementName); </li></ul><ul><li>// is there anything to do? </li></ul><ul><li>if (elements == null) { </li></ul><ul><li>return; </li></ul><ul><li>} </li></ul><ul><li>// print all elements </li></ul><ul><li>int elementCount = elements.getLength(); </li></ul><ul><li>System.out.println (&quot;Count = &quot; + elementCount); </li></ul><ul><li>for (int i = 0; i < elementCount; i++) { </li></ul><ul><li>Element element = (Element) elements.item(i); </li></ul><ul><li>Node node = element.getFirstChild(); </li></ul><ul><li>System.out.println(&quot;Element Name = &quot; + element.getNodeName()); </li></ul><ul><li>System.out.println(&quot;Element Type = &quot; + node.getNodeType()); </li></ul><ul><li>System.out.println(&quot;Element Value = &quot; + node.getNodeValue()); </li></ul><ul><li>System.out.println(&quot;Has attributes = &quot; + node.hasAttributes()); </li></ul><ul><li>} </li></ul><ul><li>} </li></ul><ul><li>catch (DOMException e2) { </li></ul><ul><li>System.out.println (&quot;Exception: &quot; + e2); </li></ul><ul><li>} </li></ul><ul><li>catch (Exception e3) { </li></ul><ul><li>System.out.println (&quot;Exception: &quot; + e3); </li></ul><ul><li>} </li></ul><ul><li>} </li></ul><ul><li>} </li></ul>
  65. 65. Problem <ul><li>Write a program to display element names and their attribute names and values </li></ul>
  66. 66. Solution <ul><li>package domexamples; </li></ul><ul><li>import org.w3c.dom.*; </li></ul><ul><li>import org.w3c.dom.bootstrap.*; </li></ul><ul><li>import org.w3c.dom.ls.*; </li></ul><ul><li>public class DOMAttributesExample { </li></ul><ul><li>public static void main(String[] args) { </li></ul><ul><li>NodeList elements; </li></ul><ul><li>String elementName = &quot;cd&quot;; </li></ul><ul><li>try { </li></ul><ul><li>DOMImplementationRegistry registry = DOMImplementationRegistry.newInstance(); </li></ul><ul><li>DOMImplementation domImpl = registry.getDOMImplementation(&quot;LS 3.0&quot;); </li></ul><ul><li>// Casting </li></ul><ul><li>DOMImplementationLS implLS = (DOMImplementationLS) domImpl; </li></ul><ul><li>LSParser parser = implLS.createLSParser(DOMImplementationLS.MODE_SYNCHRONOUS, </li></ul><ul><li>&quot;http://www.w3.org/2001/XMLSchema&quot;); </li></ul><ul><li>DOMConfiguration config = parser.getDomConfig(); </li></ul><ul><li>// Set error handler </li></ul><ul><li>DOMErrorHandlerImpl errorHandler = new DOMErrorHandlerImpl(); </li></ul><ul><li>config.setParameter(&quot;error-handler&quot;, errorHandler); </li></ul><ul><li>// Set schema validation parameters </li></ul><ul><li>// config.setParameter(&quot;validate&quot;, Boolean.TRUE); </li></ul><ul><li>// config.setParameter(&quot;schema-type&quot;, &quot;http://www.w3.org/2001/XML/Schema&quot;); </li></ul><ul><li>// config.setParameter(&quot;validate-if-schema&quot;, Boolean.TRUE); </li></ul><ul><li>// config.setParameter(&quot;schema-location&quot;, &quot;book.xsd&quot;); </li></ul><ul><li>Document document = parser.parseURI(&quot;CDCatalog.xml&quot;); </li></ul><ul><li>Element root = document.getDocumentElement(); </li></ul><ul><li>System.out.println(&quot;In main ... XML file openend successfully ...&quot;); </li></ul><ul><li>elements = document.getElementsByTagName(elementName); </li></ul><ul><li>// is there anything to do? </li></ul><ul><li>if (elements == null) { </li></ul><ul><li>return; </li></ul><ul><li>} </li></ul><ul><li>// print all elements </li></ul><ul><li>int elementCount = elements.getLength(); </li></ul><ul><li>System.out.println(&quot;Count = &quot; + elementCount); </li></ul><ul><li>for (int i = 0; i < elementCount; i++) { </li></ul><ul><li>Element element = (Element) elements.item(i); </li></ul><ul><li>System.out.println(&quot;Element Name = &quot; + element.getNodeName()); </li></ul><ul><li>System.out.println(&quot;Element Type = &quot; + element.getNodeType()); </li></ul><ul><li>System.out.println(&quot;Element Value = &quot; + element.getNodeValue()); </li></ul><ul><li>System.out.println(&quot;Has attributes = &quot; + element.hasAttributes()); </li></ul><ul><li>// If attributes exist, print them </li></ul><ul><li>if (element.hasAttributes()) { </li></ul><ul><li>// if it does, store it in a NamedNodeMap object </li></ul><ul><li>NamedNodeMap AttributesList = element.getAttributes(); </li></ul><ul><li>// iterate through the NamedNodeMap and get the attribute names and values </li></ul><ul><li>for (int j = 0; j < AttributesList.getLength(); j++) { </li></ul><ul><li>System.out.println(&quot;Attribute: &quot; + </li></ul><ul><li>AttributesList.item(j).getNodeName() + &quot; = &quot; + </li></ul><ul><li>AttributesList.item(j).getNodeValue()); </li></ul><ul><li>} </li></ul><ul><li>} </li></ul><ul><li>} </li></ul><ul><li>} catch (Exception e1) { </li></ul><ul><li>System.out.println(&quot;Exception: &quot; + e1); </li></ul><ul><li>} </li></ul><ul><li>} </li></ul><ul><li>} </li></ul>
  67. 67. Problem <ul><li>For a given element, find out all the child elements and display their types </li></ul>
  68. 68. Solution <ul><li>import org.w3c.dom.*; </li></ul><ul><li>package domexamples; </li></ul><ul><li>import org.w3c.dom.*; </li></ul><ul><li>import org.w3c.dom.bootstrap.*; </li></ul><ul><li>import org.w3c.dom.ls.*; </li></ul><ul><li>public class DOMGetChildrenOfAnElement { </li></ul><ul><li>public static void main (String[] args) { </li></ul><ul><li>NodeList elements, Children; </li></ul><ul><li>String elementName = &quot;cd&quot;; </li></ul><ul><li>String local = &quot;&quot;; </li></ul><ul><li>try { </li></ul><ul><li>DOMImplementationRegistry registry = DOMImplementationRegistry.newInstance(); </li></ul><ul><li>DOMImplementation domImpl = registry.getDOMImplementation(&quot;LS 3.0&quot;); </li></ul><ul><li>// Casting </li></ul><ul><li>DOMImplementationLS implLS = (DOMImplementationLS) domImpl; </li></ul><ul><li>LSParser parser = implLS.createLSParser(DOMImplementationLS.MODE_SYNCHRONOUS, </li></ul><ul><li>&quot;http://www.w3.org/2001/XMLSchema&quot;); </li></ul><ul><li>DOMConfiguration config = parser.getDomConfig(); </li></ul><ul><li>// Set error handler </li></ul><ul><li>DOMErrorHandlerImpl errorHandler = new DOMErrorHandlerImpl(); </li></ul><ul><li>config.setParameter(&quot;error-handler&quot;, errorHandler); </li></ul><ul><li>// Set schema validation parameters </li></ul><ul><li>// config.setParameter(&quot;validate&quot;, Boolean.TRUE); </li></ul><ul><li>// config.setParameter(&quot;schema-type&quot;, &quot;http://www.w3.org/2001/XML/Schema&quot;); </li></ul><ul><li>// config.setParameter(&quot;validate-if-schema&quot;, Boolean.TRUE); </li></ul><ul><li>// config.setParameter(&quot;schema-location&quot;, &quot;book.xsd&quot;); </li></ul><ul><li>Document document = parser.parseURI(&quot;CDCatalog.xml&quot;); </li></ul><ul><li>Element root = document.getDocumentElement(); </li></ul><ul><li>System.out.println (&quot;In main ... XML file openend successfully ...&quot;); </li></ul><ul><li>elements = document.getElementsByTagName(elementName); </li></ul><ul><li>// is there anything to do? </li></ul><ul><li>if (elements == null) { </li></ul><ul><li>return; </li></ul><ul><li>} </li></ul><ul><li>// print all elements </li></ul><ul><li>int elementCount = elements.getLength(); </li></ul><ul><li>System.out.println (&quot;Count = &quot; + elementCount); </li></ul><ul><li>for (int i = 0; i < elementCount; i++) { </li></ul><ul><li>Element element = (Element) elements.item(i); </li></ul><ul><li>Node node = element.getFirstChild(); </li></ul><ul><li>System.out.println(&quot;Element Name = &quot; + element.getNodeName()); </li></ul><ul><li>System.out.println(&quot;Element Type = &quot; + node.getNodeType()); </li></ul><ul><li>System.out.println(&quot;Element Value = &quot; + node.getNodeValue()); </li></ul><ul><li>System.out.println(&quot;Has attributes = &quot; + node.hasAttributes()); </li></ul><ul><li>// Find out if child nodes exist for this element </li></ul><ul><li>Children = element.getChildNodes(); </li></ul><ul><li>if (Children != null) { </li></ul><ul><li>for (int j=0; j< Children.getLength(); j++) { </li></ul><ul><li>local = Children.item(j).getNodeName(); </li></ul><ul><li>System.out.println (&quot;Child element name = &quot; + local); </li></ul><ul><li>} </li></ul><ul><li>} </li></ul><ul><li>} </li></ul><ul><li>} </li></ul><ul><li>catch (Exception e) { </li></ul><ul><li>System.out.println (&quot;Exception: &quot; + e); </li></ul><ul><li>} </li></ul><ul><li>} </li></ul><ul><li>} </li></ul>
  69. 69. Node Types <ul><li>1 ELEMENT_NODE Element The element name 2 ATTRIBUTE_NODE Attribute The attribute name 3 TEXT_NODE Text #text 4 CDATA_SECTION_NODE CDATA #cdata-section 5 ENTITY_REFERENCE_NODE Entity reference The entity reference name 6 ENTITY_NODE Entity The entity name 7 PROCESSING_INSTRUCTION_NODE PI The PI target 8 COMMENT_NODE Comment #comment 9 DOCUMENT_NODE Document #document 10 DOCUMENT_TYPE_NODE DocType Root element 11 DOCUMENT_FRAGMENT_NODE DocumentFragment #document-fragment 12 NOTATION_NODE Notation The notation name </li></ul>
  70. 70. Problem <ul><li>Write a program to create XML contents dynamically and write them to a file on the disk </li></ul>
  71. 71. Solution <ul><li>/* </li></ul><ul><li>* To change this template, choose Tools | Templates </li></ul><ul><li>* and open the template in the editor. </li></ul><ul><li>*/ </li></ul><ul><li>package domexamples; </li></ul><ul><li>import org.w3c.dom.*; </li></ul><ul><li>import org.w3c.dom.bootstrap.DOMImplementationRegistry; </li></ul><ul><li>import org.w3c.dom.ls.*; </li></ul><ul><li>import javax.xml.parsers.*; </li></ul><ul><li>/** </li></ul><ul><li>* </li></ul><ul><li>* @author atulk </li></ul><ul><li>*/ </li></ul><ul><li>public class DOMNewXMLFileCreator { </li></ul><ul><li>public void saveDocument () { </li></ul><ul><li>try { </li></ul><ul><li>DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); </li></ul><ul><li>DocumentBuilder builder = factory.newDocumentBuilder(); </li></ul><ul><li>Document document = builder.newDocument(); </li></ul><ul><li>Element catalog = document.createElement(&quot;catalog&quot;); </li></ul><ul><li>catalog.setAttribute(&quot;publisher&quot;, &quot;McGraw-Hill&quot;); </li></ul><ul><li>document.appendChild (catalog); </li></ul><ul><li>Element journal = document.createElement(&quot;journal&quot;); </li></ul><ul><li>journal.setAttribute(&quot;edition&quot;, &quot;October 2005&quot;); </li></ul><ul><li>journal.setAttribute(&quot;section&quot;, &quot;XML&quot;); </li></ul><ul><li>catalog.appendChild(journal); </li></ul><ul><li>Element article = document.createElement(&quot;article&quot;); </li></ul><ul><li>journal.appendChild (article); </li></ul><ul><li>Element title = document.createElement(&quot;title&quot;); </li></ul><ul><li>title.appendChild (document.createTextNode(&quot;DOM Parsing&quot;)); </li></ul><ul><li>article.appendChild (title); </li></ul><ul><li>Element author = document.createElement(&quot;author&quot;); </li></ul><ul><li>author.appendChild (document.createTextNode(&quot;Anonymous&quot;)); </li></ul><ul><li>article.appendChild(author); </li></ul><ul><li>DOMImplementationRegistry registry = DOMImplementationRegistry.newInstance(); </li></ul><ul><li>DOMImplementation domImpl = registry.getDOMImplementation(&quot;LS 3.0&quot;); </li></ul><ul><li>DOMImplementationLS implLS = (DOMImplementationLS) domImpl; </li></ul><ul><li>LSSerializer dom3Writer = implLS.createLSSerializer(); </li></ul><ul><li>LSOutput output = implLS.createLSOutput(); </li></ul><ul><li>System.out.println (&quot;Outputting XML Document ...&quot;); </li></ul><ul><li>output.setByteStream (System.out); </li></ul><ul><li>output.setEncoding (&quot;UTF-8&quot;); </li></ul><ul><li>dom3Writer.write (document, output); </li></ul><ul><li>System.out.println (&quot;nn&quot; + &quot;Outputting the journal node&quot; + &quot;n&quot;); </li></ul><ul><li>dom3Writer.write(journal, output); </li></ul><ul><li>String nodeString = dom3Writer.writeToString(journal); </li></ul><ul><li>} </li></ul><ul><li>catch (Exception e) { </li></ul><ul><li>e.printStackTrace(); </li></ul><ul><li>} </li></ul><ul><li>} </li></ul><ul><li>public static void main (String [] args) { </li></ul><ul><li>DOMNewXMLFileCreator fc = new DOMNewXMLFileCreator (); </li></ul><ul><li>fc.saveDocument(); </li></ul><ul><li>} </li></ul><ul><li>} </li></ul>
  72. 72. Stream API (StAX)
  73. 73. Creating an XML Document using StAX <ul><li>package xmlbook.chapter7; </li></ul><ul><li>import java.io.*; </li></ul><ul><li>import java.util.*; </li></ul><ul><li>import javax.xml.stream.XMLOutputFactory; </li></ul><ul><li>import javax.xml.stream.XMLStreamWriter; </li></ul><ul><li>import javax.xml.stream.XMLStreamException; </li></ul><ul><li>public class CreateFTXML { </li></ul><ul><li>public void CreateXML(int fromAccount, int toAccount, int amount) { </li></ul><ul><li>// Create XMLOutputFactory object </li></ul><ul><li>XMLOutputFactory outputFactory = XMLOutputFactory.newInstance(); </li></ul><ul><li>try { </li></ul><ul><li>// Create the XMLStreamWriter object </li></ul><ul><li>FileWriter fileWriter = new FileWriter(&quot;d:FT.xml&quot;); </li></ul><ul><li>XMLStreamWriter writer = outputFactory.createXMLStreamWriter(fileWriter); </li></ul><ul><li>// XMLStreamWriter writer = outputFactory.createXMLStreamWriter(System.out); </li></ul><ul><li>// Write XML data now </li></ul><ul><li>writer.writeStartDocument(&quot;1.0&quot;); </li></ul><ul><li>writer.writeComment(&quot;Funds Transfer Data&quot;); </li></ul><ul><li>writer.writeStartElement(&quot;FundsTransfer&quot;); </li></ul><ul><li>writer.writeStartElement(&quot;FromAccount&quot;); </li></ul><ul><li>writer.writeCharacters(Integer.toString(fromAccount)); </li></ul><ul><li>writer.writeEndElement(); </li></ul><ul><li>writer.writeStartElement(&quot;ToAccount&quot;); </li></ul><ul><li>writer.writeCharacters(Integer.toString(toAccount)); </li></ul><ul><li>writer.writeEndElement(); </li></ul><ul><li>writer.writeStartElement(&quot;Amount&quot;); </li></ul><ul><li>writer.writeCharacters(Integer.toString(amount)); </li></ul><ul><li>writer.writeEndElement(); </li></ul><ul><li>writer.writeEndElement(); // for FundsTransfer element </li></ul><ul><li>writer.writeEndDocument(); </li></ul><ul><li>writer.flush(); </li></ul><ul><li>writer.close(); </li></ul><ul><li>} catch (IOException e) { </li></ul><ul><li>e.printStackTrace(); </li></ul><ul><li>} catch (XMLStreamException e) { </li></ul><ul><li>e.printStackTrace(); </li></ul><ul><li>} </li></ul><ul><li>} </li></ul><ul><li>} </li></ul>
  74. 74. Using StAX to Read <ul><li>package xmlbook.chapter7; </li></ul><ul><li>import java.io.*; </li></ul><ul><li>import java.util.*; </li></ul><ul><li>import javax.xml.stream.XMLInputFactory; </li></ul><ul><li>import javax.xml.stream.XMLStreamReader; </li></ul><ul><li>import javax.xml.stream.XMLStreamConstants; </li></ul><ul><li>import javax.xml.stream.XMLStreamException; </li></ul><ul><li>public class ReadFTXML { </li></ul><ul><li>public int parseXML(String whichElement) { </li></ul><ul><li>XMLInputFactory inputFactory = XMLInputFactory.newInstance(); </li></ul><ul><li>try { </li></ul><ul><li>// create an XMLStreamReader object </li></ul><ul><li>FileReader fileReader = new FileReader(&quot;d:FT.xml&quot;); </li></ul><ul><li>XMLStreamReader reader = inputFactory.createXMLStreamReader(fileReader); </li></ul><ul><li>// read the XML now </li></ul><ul><li>while (reader.hasNext()) { </li></ul><ul><li>if (reader.getEventType() == XMLStreamConstants.START_ELEMENT) { </li></ul><ul><li>String elementName = reader.getLocalName(); </li></ul><ul><li>if (elementName.equalsIgnoreCase(whichElement)) { </li></ul><ul><li>String valueToReturn = reader.getElementText(); </li></ul><ul><li>return Integer.parseInt(valueToReturn); </li></ul><ul><li>} </li></ul><ul><li>} </li></ul><ul><li>reader.next(); </li></ul><ul><li>} </li></ul><ul><li>} catch (FileNotFoundException e) { </li></ul><ul><li>e.printStackTrace(); </li></ul><ul><li>} catch (XMLStreamException e) { </li></ul><ul><li>e.printStackTrace(); </li></ul><ul><li>} </li></ul><ul><li>return -1; // In the case of an error </li></ul><ul><li>} </li></ul><ul><li>} </li></ul>
  75. 75. XML and ASP.NET – An Overview
  76. 76. XmlReader and XmlWriter <ul><li>XMLReader </li></ul><ul><ul><li>Pull-style API for XML </li></ul></ul><ul><ul><li>Forward-only, read-only access to XML documents </li></ul></ul><ul><ul><li>XMLReader is an abstract class that other classes derive from, to provide specific concrete instances such as XmlTextReader and XmlNodeReader </li></ul></ul><ul><ul><li>In ASP.NET 2.0, XMLReader is a factory </li></ul></ul><ul><ul><ul><li>We need not specify which implementation of XMLReader needs to be used </li></ul></ul></ul><ul><ul><ul><li>We use a static Create method, and supply necessary parameters and let .NET decide how to instantiate it </li></ul></ul></ul>
  77. 77. Example – XML Document <ul><li><? xml version =&quot;1.0&quot; encoding =&quot;utf-8&quot; ?> </li></ul><ul><li>< bookstore > </li></ul><ul><li>< book genre =&quot;autobiography&quot; publicationdate =&quot;1981&quot; ISBN =&quot;1-861003-11-0&quot;> </li></ul><ul><li>< title >The Autobiography of Benjamin Franklin</ title > </li></ul><ul><li>< author > </li></ul><ul><li>< first-name >Benjamin</ first-name > </li></ul><ul><li>< last-name >Franklin</ last-name > </li></ul><ul><li></ author > </li></ul><ul><li>< price >8.99</ price > </li></ul><ul><li></ book > </li></ul><ul><li>< book genre =&quot;novel&quot; publicationdate =&quot;1967&quot; ISBN =&quot;0-201-65512-2&quot;> </li></ul><ul><li>< title >The Confidence Man</ title > </li></ul><ul><li>< author > </li></ul><ul><li>< first-name >Herman</ first-name > </li></ul><ul><li>< last-name >Melville</ last-name > </li></ul><ul><li></ author > </li></ul><ul><li>< price >11.99</ price > </li></ul><ul><li></ book > </li></ul><ul><li>< book genre =&quot;philosophy&quot; publicationdate =&quot;1991&quot; ISBN =&quot;1-861001-57-6&quot;> </li></ul><ul><li>< title >The Gorgias</ title > </li></ul><ul><li>< author > </li></ul><ul><li>< first-name >Sidas</ first-name > </li></ul><ul><li>< last-name >Plato</ last-name > </li></ul><ul><li></ author > </li></ul><ul><li>< price >9.99</ price > </li></ul><ul><li></ book > </li></ul><ul><li></ bookstore > </li></ul>
  78. 78. Example – ASP.NET Page <ul><li>using System; </li></ul><ul><li>using System.Data; </li></ul><ul><li>using System.Configuration; </li></ul><ul><li>using System.Collections; </li></ul><ul><li>using System.Web; </li></ul><ul><li>using System.Web.Security; </li></ul><ul><li>using System.Web.UI; </li></ul><ul><li>using System.Web.UI.WebControls; </li></ul><ul><li>using System.Web.UI.WebControls.WebParts; </li></ul><ul><li>using System.Web.UI.HtmlControls; </li></ul><ul><li>using System.Xml; </li></ul><ul><li>using System.IO; </li></ul><ul><li>public partial class XMLReader2 : System.Web.UI.Page </li></ul><ul><li>{ </li></ul><ul><li>protected void Page_Load(object sender, EventArgs e) </li></ul><ul><li>{ </li></ul><ul><li>int bookCount = 0; </li></ul><ul><li>XmlReaderSettings settings = new XmlReaderSettings(); </li></ul><ul><li>settings.IgnoreWhitespace = true; </li></ul><ul><li>settings.IgnoreComments = true; </li></ul><ul><li>string booksFile = Path.Combine(Request.PhysicalApplicationPath, &quot;Books.xml&quot;); </li></ul><ul><li>using ( XmlReader reader = XmlReader.Create(booksFile, settings)) </li></ul><ul><li>{ </li></ul><ul><li>while (reader.Read()) </li></ul><ul><li>{ </li></ul><ul><li>if (reader.NodeType == XmlNodeType.Element && &quot;book&quot; == reader.LocalName) </li></ul><ul><li>{ </li></ul><ul><li>bookCount++; </li></ul><ul><li>} </li></ul><ul><li>} </li></ul><ul><li>} </li></ul><ul><li>Response.Write( String.Format( &quot;Found {0} books!&quot;, bookCount)); </li></ul><ul><li>} </li></ul><ul><li>} </li></ul>
  79. 79. Validating an XML Against a Schema <ul><li>using System.Xml.Schema; </li></ul><ul><li>using System; </li></ul><ul><li>using System.Xml; </li></ul><ul><li>using System.IO; </li></ul><ul><li>public partial class XMLReader3 : System.Web.UI.Page </li></ul><ul><li>{ </li></ul><ul><li>protected void Page_Load(object sender, EventArgs e) </li></ul><ul><li>{ </li></ul><ul><li>int bookCount = 0; </li></ul><ul><li>XmlReaderSettings settings = new XmlReaderSettings(); </li></ul><ul><li>string booksSchemaFile = Path.Combine(Request.PhysicalApplicationPath, &quot;books.xsd&quot;); </li></ul><ul><li>settings.Schemas.Add ( null, XmlReader.Create (booksSchemaFile)); </li></ul><ul><li>settings.ValidationType = ValidationType.Schema; </li></ul><ul><li>settings.ValidationFlags = XmlSchemaValidationFlags.ReportValidationWarnings; </li></ul><ul><li>settings.ValidationEventHandler += new ValidationEventHandler (settings_ValidationEventHandler); </li></ul><ul><li>settings.IgnoreWhitespace = true; </li></ul><ul><li>settings.IgnoreComments = true; </li></ul><ul><li>string booksFile = Path.Combine(Request.PhysicalApplicationPath, &quot;Books.xml&quot;); </li></ul><ul><li>using ( XmlReader reader = XmlReader.Create(booksFile, settings)) </li></ul><ul><li>{ </li></ul><ul><li>while (reader.Read()) </li></ul><ul><li>{ </li></ul><ul><li>if (reader.NodeType == XmlNodeType.Element && &quot;book&quot; == reader.LocalName) </li></ul><ul><li>{ </li></ul><ul><li>bookCount++; </li></ul><ul><li>} </li></ul><ul><li>} </li></ul><ul><li>} </li></ul><ul><li>Response.Write( String.Format( &quot;Found {0} books!&quot;, bookCount)); </li></ul><ul><li>} </li></ul><ul><li>void settings_ValidationEventHandler(object sender, System.Xml.Schema. ValidationEventArgs e) </li></ul><ul><li>{ </li></ul><ul><li>Response.Write(e.Message); </li></ul><ul><li>} </li></ul><ul><li>} </li></ul>
  80. 80. Creating an XML Document <ul><li>using System.Xml.Schema; </li></ul><ul><li>using System; </li></ul><ul><li>using System.Xml; </li></ul><ul><li>using System.IO; </li></ul><ul><li>public partial class XMLReader3 : System.Web.UI.Page </li></ul><ul><li>{ </li></ul><ul><li>protected void Page_Load(object sender, EventArgs e) </li></ul><ul><li>{ </li></ul><ul><li>int bookCount = 0; </li></ul><ul><li>XmlReaderSettings settings = new XmlReaderSettings(); </li></ul><ul><li>string booksSchemaFile = Path.Combine(Request.PhysicalApplicationPath, &quot;books.xsd&quot;); </li></ul><ul><li>settings.Schemas.Add ( null, XmlReader.Create (booksSchemaFile)); </li></ul><ul><li>settings.ValidationType = ValidationType.Schema; </li></ul><ul><li>settings.ValidationFlags = XmlSchemaValidationFlags.ReportValidationWarnings; </li></ul><ul><li>settings.ValidationEventHandler += new ValidationEventHandler (settings_ValidationEventHandler); </li></ul><ul><li>settings.IgnoreWhitespace = true; </li></ul><ul><li>settings.IgnoreComments = true; </li></ul><ul><li>string booksFile = Path.Combine(Request.PhysicalApplicationPath, &quot;Books.xml&quot;); </li></ul><ul><li>using ( XmlReader reader = XmlReader.Create(booksFile, settings)) </li></ul><ul><li>{ </li></ul><ul><li>while (reader.Read()) </li></ul><ul><li>{ </li></ul><ul><li>if (reader.NodeType == XmlNodeType.Element && &quot;book&quot; == reader.LocalName) </li></ul><ul><li>{ </li></ul><ul><li>bookCount++; </li></ul><ul><li>} </li></ul><ul><li>} </li></ul><ul><li>} </li></ul><ul><li>Response.Write( String.Format( &quot;Found {0} books!&quot;, bookCount)); </li></ul><ul><li>} </li></ul><ul><li>void settings_ValidationEventHandler(object sender, System.Xml.Schema. ValidationEventArgs e) </li></ul><ul><li>{ </li></ul><ul><li>Response.Write(e.Message); </li></ul><ul><li>} </li></ul><ul><li>} </li></ul>
  81. 81. Thank you! Any Questions?
  1. A particular slide catching your eye?

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

×