SlideShare a Scribd company logo
FLASH #1




JAVA & XML PARSER
Agenda

●   SAX
●   DOM
●   STAX
●   JAXB
●   Conclusion
SAX
•   Sequential reading of XML files. Can not be
    used to create XML documents.
•   SAX provides an Event-Driven XML
    Processing following the Push-Parsing
    Model. What this model means is that in SAX
•   Applications will register Listeners in the form
    of Handlers to the Parser and will get notified
    through Call-back methods.
•   Here the SAX Parser takes the control over
    Application thread by Pushing Events to the
    Application.
EXAMPLE
<?xml version="1.0"?>
<howto>
  <topic>
      <title>Java</title>
      <url>http://www.rgagnon/javahowto.htm</url>
  </topic>
    <topic>
      <title>PowerBuilder</title>
      <url>http://www.rgagnon/pbhowto.htm</url>
  </topic>
      <topic>
        <title>Javascript</title>
        <url>http://www.rgagnon/jshowto.htm</url>
  </topic>
      <topic>
        <title>VBScript</title>
        <url>http://www.rgagnon/vbshowto.htm</url>
  </topic>
</howto>

                                                     Title: Java
                                                     Url: http://www.rgagnon/javahowto.htm
                                                     Title: PowerBuilder
                                                     Url: http://www.rgagnon/pbhowto.htm
                                                     Title: Javascript
                                                     Url: http://www.rgagnon/jshowto.htm
                                                     Title: VBScript
                                                     Url: http://www.rgagnon/vbshowto.htm
// jdk1.4.1
import java.io.*;
import org.xml.sax.*;
import org.xml.sax.helpers.*;
// using SAX
public class HowToListerSAX {
  class HowToHandler extends DefaultHandler {
    boolean title = false;
    boolean url   = false;
    public void startElement(String nsURI, String strippedName,
                            String tagName, Attributes attributes)
       throws SAXException {
     if (tagName.equalsIgnoreCase("title"))
        title = true;
     if (tagName.equalsIgnoreCase("url"))
        url = true;
    }
    public void characters(char[] ch, int start, int length) {
     if (title) {
       System.out.println("Title: " + new String(ch, start, length));
       title = false;
       }
     else if (url) {
       System.out.println("Url: " + new String(ch, start,length));
       url = false;
       }
     }
    }
    public void list( ) throws Exception {
       XMLReader parser =
          XMLReaderFactory.createXMLReader
            ("org.apache.crimson.parser.XMLReaderImpl");
       parser.setContentHandler(new HowToHandler( ));
       parser.parse("howto.xml");
       }
    public static void main(String[] args) throws Exception {
       new HowToListerSAX().list( );
       }
}
                                                                        I recommend not to use SAX.
DOM

●   The DOM is an interface that exposes an XML
    document as a tree structure comprised of
    nodes.
●   The DOM allows you to programmatically
    navigate the tree and add, change and delete
    any of its elements.
DOM
/ jdk1.4.1
import java.io.File;
import javax.xml.parsers.*;
import org.w3c.dom.*;
// using DOM
public class HowtoListerDOM {
 public static void main(String[] args) {
   File file = new File("howto.xml");
   try {
     DocumentBuilder builder =
       DocumentBuilderFactory.newInstance().newDocumentBuilder();
     Document doc = builder.parse(file);
     NodeList nodes = doc.getElementsByTagName("topic");
     for (int i = 0; i < nodes.getLength(); i++) {
       Element element = (Element) nodes.item(i);
       NodeList title = element.getElementsByTagName("title");
       Element line = (Element) title.item(0);
       System.out.println("Title: " + getCharacterDataFromElement(line));
       NodeList url = element.getElementsByTagName("url");
       line = (Element) url.item(0);
       System.out.println("Url: " + getCharacterDataFromElement(line));
     }
   }
   catch (Exception e) {
      e.printStackTrace();
   }
 }
 public static String getCharacterDataFromElement(Element e) {
   Node child = e.getFirstChild();
   if (child instanceof CharacterData) {
     CharacterData cd = (CharacterData) child;
       return cd.getData();
     }
   return "?";
 }
}

                                                                        I recommend not to use DOM.
STAX
●   Streaming API for XML, simply called StaX, is
    an API for reading and writing XML
    Documents.
●   StaX is a Pull-Parsing model. Application can
    take the control over parsing the XML
    documents by pulling (taking) the events from
    the parser.
●   The core StaX API falls into two categories
    and they are listed below. They are
        –   Cursor API
        –   Event Iterator API
"Pull" vs. "Push" Style API


SAX PARSER             YOUR APP




YOUR APP            STAX PARSER




               Stax is cool if you need the control over the XML
               flow. Otherwise use JAXB.
EXEMPLE
<?xml version="1.0" encoding="UTF-8"?>
<config>
  <mode>1</mode>
  <unit>900</unit>
  <current>1</current>
  <interactive>1</interactive>
</config>



import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import javax.xml.stream.XMLEventReader;
import javax.xml.stream.XMLInputFactory;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.events.XMLEvent;
public class ConfigFileStaX2 {
    private String configFile;
    public void setFile(String configFile) {
        this.configFile = configFile;
    }
 public static void main(String args[]) {
        ConfigFileStaX2 read = new ConfigFileStaX2();
        read.setFile("config.xml");
        read.readConfig();
    }

}
public void readConfig() {
       try {
           // First create a new XMLInputFactory
           XMLInputFactory inputFactory = XMLInputFactory.newInstance();
           // Setup a new eventReader
           InputStream in = new FileInputStream(configFile);
           XMLEventReader eventReader = inputFactory.createXMLEventReader(in);
           // Read the XML document
           while (eventReader.hasNext()) {
               XMLEvent event = eventReader.nextEvent();
               if (event.isStartElement()) {
                   if (event.asStartElement().getName().getLocalPart() == ("mode")) {
                       event = eventReader.nextEvent();
                       System.out.println(event.asCharacters().getData());
                       continue;
                   }
                   if (event.asStartElement().getName().getLocalPart() == ("unit")) {
                       event = eventReader.nextEvent();
                       System.out.println(event.asCharacters().getData());
                       continue;
                   }
                   if (event.asStartElement().getName().getLocalPart() == ("current")) {
                       event = eventReader.nextEvent();
                       System.out.println(event.asCharacters().getData());
                       continue;
                   }
                   if (event.asStartElement().getName().getLocalPart() == ("interactive")) {
                       event = eventReader.nextEvent();
                       System.out.println(event.asCharacters().getData());
                       continue;
                   }
               }
           }
       } catch (Exception e) {
           e.printStackTrace();
       }
   }
PATTERN
<?xml version="1.0" encoding="utf-8"?>
<feed xmlns="http://www.w3.org/2005/Atom">
 <title>Simple Atom Feed File</title>
 <subtitle>Using StAX to read feed files</subtitle>
 <link href="http://example.org/"/>
 <updated>2006-01-01T18:30:02Z</updated>

 <author>
   <name>Feed Author</name>
   <email>doofus@feed.com</email>
 </author>
 <entry>
   <title>StAX parsing is simple</title>
   <link href="http://www.devx.com"/>
   <updated>2006-01-01T18:30:02Z</updated>
   <summary>Lean how to use StAX</summary>
 </entry>
</feed>




public interface ComponentParser {
  public void parseElement(XMLStreamReader staxXmlReader) throws XMLStreamException;
}
public class AuthorParser implements ComponentParser{

    public void parse(XMLStreamReader staxXmlReader) throws XMLStreamException{

        // read name
        StaxUtil.moveReaderToElement("name",staxXmlReader);
        String name = staxXmlReader.getElementText();

        // read email
        StaxUtil.moveReaderToElement("email",staxXmlReader);
        String email = staxXmlReader.getElementText();

        // Do something with author data...
    }
}


                                          public class EntryParser implements ComponentParser {
                                            public void parse(XMLStreamReader staxXmlReader) throws XMLStreamException{

                                                  // read title
                                                  StaxUtil.moveReaderToElement("title",staxXmlReader);
                                                  String title = staxXmlReader.getElementText();

                                                  // read link attributes
                                                  StaxUtil.moveReaderToElement("link",staxXmlReader);
                                                  // read href attribute
                                                  String linkHref = staxXmlReader.getAttributeValue(0);

                                                  // read updated
                                                  StaxUtil.moveReaderToElement("updated",staxXmlReader);
                                                  String updated = staxXmlReader.getElementText();

                                                  // read title
                                                  StaxUtil.moveReaderToElement("summary",staxXmlReader);
                                                  String summary = staxXmlReader.getElementText();

                                                  // Do something with the data read from StAX..
                                              }
                                          }
public class StaxParser implements ComponentParser {
    private Map delegates;
    …
    public void parse(XMLStreamReader staxXmlReader) throws XMLStreamException{
      for (int event = staxXmlReader.next(); event != XMLStreamConstants.END_DOCUMENT; event = staxXmlReader.next()) {
        if (event == XMLStreamConstants.START_ELEMENT) {
          String element = staxXmlReader.getLocalName();
          // If a Component Parser is registered that can handle
          // this element delegate…
          if (delegates.containsKey(element)) {
            ComponentParser parser = (ComponentParser) delegates.get(element);
            parser.parse(staxXmlReader);
          }
        }
      } //rof
    }
}




InputStream in = this.getClass().getResourceAsStream("atom.xml");

 XMLInputFactory factory = (XMLInputFactory) XMLInputFactory.newInstance();
 XMLStreamReader staxXmlReader = (XMLStreamReader)
factory.createXMLStreamReader(in);

 StaxParser parser = new StaxParser();
 parser.registerParser("author",new AuthorParser());
 parser.registerParser("entry",new EntryParser());

 parser.parse(staxXmlReader);
JAXB
●    JAXB is a Java standard that defines how
    Java objects are converted to/from XML
    (specified using a standard set of mappings.
●    JAXB defines a programmer API for reading
    and writing Java objects to / from XML
    documents and a service provider which /
    from from XML documents allows the
    selection of the JAXB implementation
●   JAXB applies a lot of defaults thus making
    reading and writing of XML via Java very easy.
                            I recommend to use JAXB (or Stax if you
                            need more control).
Demo JAXB
XML Parser API Feature Summary

Feature            StAX              SAX               DOM
API Type           Pull, streaming   Push, streaming   In memory tree

Ease of Use        High              Medium            High

XPath Capability   Not supported     Not supported     Supported

CPU and Memory     Good              Good              Varies
Efficiency
Read XML           Supported         Supported         Supported

Write XML          Supported         Not supported     Supported
NEXT

●   JAXB + STAX
       –   http://www.javarants.com/2006/04/30/simple-
             and-efficient-xml-parsing-using-jaxb-2-0/
References

●   http://www.j2ee.me/javaee/5/docs/tutorial/doc/bnb
●   http://www.devx.com/Java/Article/30298/0/page/2
●   http://www.vogella.de/articles/JavaXML/article.htm
●   http://tutorials.jenkov.com/java-xml/stax.html
●   http://www.javarants.com/2006/04/30/simple-
    and-efficient-xml-parsing-using-jaxb-2-0/

More Related Content

What's hot (20)

PDF
Jsp standard tag_library
KP Singh
 
PDF
Xml And JSON Java
Henry Addo
 
PPTX
Xslt mule
Sindhu VL
 
DOC
Whitepaper To Study Filestream Option In Sql Server
Shahzad
 
PPTX
PostgreSQL- An Introduction
Smita Prasad
 
ODP
Xml processing in scala
Knoldus Inc.
 
PPTX
04 data accesstechnologies
Bat Programmer
 
PPT
Ajax
Manav Prasad
 
PDF
spring-tutorial
Arjun Shanka
 
PDF
Session06 handling xml data
kendyhuu
 
PDF
Client Server Communication on iOS
Make School
 
PPTX
Cursors, triggers, procedures
Vaibhav Kathuria
 
PDF
Core Java tutorial at Unit Nexus
Unit Nexus Pvt. Ltd.
 
PPTX
Mule properties
Karnam Karthik
 
PPTX
Mule system properties
Karnam Karthik
 
PDF
Simple Jdbc With Spring 2.5
David Motta Baldarrago
 
PPTX
Ado.net by Awais Majeed
Awais Majeed
 
PPTX
Jdbc ja
DEEPIKA T
 
PDF
24sax
Adil Jafri
 
PPT
oracle plsql training | oracle online training | oracle plsql demo | oracle p...
Nancy Thomas
 
Jsp standard tag_library
KP Singh
 
Xml And JSON Java
Henry Addo
 
Xslt mule
Sindhu VL
 
Whitepaper To Study Filestream Option In Sql Server
Shahzad
 
PostgreSQL- An Introduction
Smita Prasad
 
Xml processing in scala
Knoldus Inc.
 
04 data accesstechnologies
Bat Programmer
 
spring-tutorial
Arjun Shanka
 
Session06 handling xml data
kendyhuu
 
Client Server Communication on iOS
Make School
 
Cursors, triggers, procedures
Vaibhav Kathuria
 
Core Java tutorial at Unit Nexus
Unit Nexus Pvt. Ltd.
 
Mule properties
Karnam Karthik
 
Mule system properties
Karnam Karthik
 
Simple Jdbc With Spring 2.5
David Motta Baldarrago
 
Ado.net by Awais Majeed
Awais Majeed
 
Jdbc ja
DEEPIKA T
 
24sax
Adil Jafri
 
oracle plsql training | oracle online training | oracle plsql demo | oracle p...
Nancy Thomas
 

Viewers also liked (9)

PDF
XML Introduction
Marco Bresciani
 
PPT
Xml Presentation-3
Sudharsan S
 
PPSX
Entity beans in java
Acp Jamod
 
PPTX
Introduction to EJB
Return on Intelligence
 
PPT
EJB .
ayyagari.vinay
 
PPTX
Introduction to xml
Gtu Booker
 
PPT
Introduction to XML
yht4ever
 
PDF
Enterprise JavaBeans(EJB)
Armen Arzumanyan
 
XML Introduction
Marco Bresciani
 
Xml Presentation-3
Sudharsan S
 
Entity beans in java
Acp Jamod
 
Introduction to EJB
Return on Intelligence
 
Introduction to xml
Gtu Booker
 
Introduction to XML
yht4ever
 
Enterprise JavaBeans(EJB)
Armen Arzumanyan
 
Ad

Similar to Xml & Java (20)

PDF
Parsing XML Data
Mu Chun Wang
 
PPT
Processing XML with Java
BG Java EE Course
 
PDF
SAX, DOM & JDOM parsers for beginners
Hicham QAISSI
 
PPT
Sax Dom Tutorial
vikram singh
 
PDF
Stax parser
ShanmukhaChariK
 
PDF
Ch23
preetamju
 
PPT
XML SAX PARSING
Eviatar Levy
 
PPT
Xml Java
cbee48
 
PPTX
java API for XML DOM
Surinder Kaur
 
PPT
SAX PARSER
Saranya Arunprasath
 
PPT
Xm lparsers
Suman Lata
 
PDF
IT6801-Service Oriented Architecture-Unit-2-notes
Ramco Institute of Technology, Rajapalayam, Tamilnadu, India
 
PPTX
Java and XML
Raji Ghawi
 
PDF
25dom
Adil Jafri
 
PDF
IQPC Canada XML 2001: How to Use XML Parsing to Enhance Electronic Communication
Ted Leung
 
PPT
Java XML Parsing
srinivasanjayakumar
 
PDF
XML and Web Services with Groovy
Paul King
 
PDF
Advanced Web Programming Chapter 12
RohanMistry15
 
PPTX
Sax parser
Mahara Jothi
 
PPT
Xml parsers
Manav Prasad
 
Parsing XML Data
Mu Chun Wang
 
Processing XML with Java
BG Java EE Course
 
SAX, DOM & JDOM parsers for beginners
Hicham QAISSI
 
Sax Dom Tutorial
vikram singh
 
Stax parser
ShanmukhaChariK
 
Ch23
preetamju
 
XML SAX PARSING
Eviatar Levy
 
Xml Java
cbee48
 
java API for XML DOM
Surinder Kaur
 
SAX PARSER
Saranya Arunprasath
 
Xm lparsers
Suman Lata
 
IT6801-Service Oriented Architecture-Unit-2-notes
Ramco Institute of Technology, Rajapalayam, Tamilnadu, India
 
Java and XML
Raji Ghawi
 
25dom
Adil Jafri
 
IQPC Canada XML 2001: How to Use XML Parsing to Enhance Electronic Communication
Ted Leung
 
Java XML Parsing
srinivasanjayakumar
 
XML and Web Services with Groovy
Paul King
 
Advanced Web Programming Chapter 12
RohanMistry15
 
Sax parser
Mahara Jothi
 
Xml parsers
Manav Prasad
 
Ad

More from Slim Ouertani (18)

PDF
merged_document_3
Slim Ouertani
 
PDF
Microservice architecture
Slim Ouertani
 
PDF
MongoDb java
Slim Ouertani
 
PDF
OCJP
Slim Ouertani
 
PDF
Effectuation: entrepreneurship for all
Slim Ouertani
 
PDF
Spring
Slim Ouertani
 
PDF
Principles of Reactive Programming
Slim Ouertani
 
PDF
Functional Programming Principles in Scala
Slim Ouertani
 
PDF
Introduction to Cmmi for development
Slim Ouertani
 
PDF
MongoDb java
Slim Ouertani
 
PDF
DBA MongoDb
Slim Ouertani
 
PDF
SOA Trainer
Slim Ouertani
 
PDF
SOA Professional
Slim Ouertani
 
PDF
SOA Architect
Slim Ouertani
 
PDF
PMP Score
Slim Ouertani
 
PPTX
Programmation fonctionnelle Scala
Slim Ouertani
 
PDF
Singleton Sum
Slim Ouertani
 
merged_document_3
Slim Ouertani
 
Microservice architecture
Slim Ouertani
 
MongoDb java
Slim Ouertani
 
Effectuation: entrepreneurship for all
Slim Ouertani
 
Principles of Reactive Programming
Slim Ouertani
 
Functional Programming Principles in Scala
Slim Ouertani
 
Introduction to Cmmi for development
Slim Ouertani
 
MongoDb java
Slim Ouertani
 
DBA MongoDb
Slim Ouertani
 
SOA Trainer
Slim Ouertani
 
SOA Professional
Slim Ouertani
 
SOA Architect
Slim Ouertani
 
PMP Score
Slim Ouertani
 
Programmation fonctionnelle Scala
Slim Ouertani
 
Singleton Sum
Slim Ouertani
 

Recently uploaded (20)

PDF
Using FME to Develop Self-Service CAD Applications for a Major UK Police Force
Safe Software
 
PDF
Blockchain Transactions Explained For Everyone
CIFDAQ
 
PPTX
WooCommerce Workshop: Bring Your Laptop
Laura Hartwig
 
PDF
From Code to Challenge: Crafting Skill-Based Games That Engage and Reward
aiyshauae
 
PPTX
UiPath Academic Alliance Educator Panels: Session 2 - Business Analyst Content
DianaGray10
 
PDF
Chris Elwell Woburn, MA - Passionate About IT Innovation
Chris Elwell Woburn, MA
 
PDF
HubSpot Main Hub: A Unified Growth Platform
Jaswinder Singh
 
PDF
LLMs.txt: Easily Control How AI Crawls Your Site
Keploy
 
PPTX
From Sci-Fi to Reality: Exploring AI Evolution
Svetlana Meissner
 
PDF
"AI Transformation: Directions and Challenges", Pavlo Shaternik
Fwdays
 
PPTX
Building Search Using OpenSearch: Limitations and Workarounds
Sease
 
PPTX
OpenID AuthZEN - Analyst Briefing July 2025
David Brossard
 
PDF
CIFDAQ Weekly Market Wrap for 11th July 2025
CIFDAQ
 
PPTX
COMPARISON OF RASTER ANALYSIS TOOLS OF QGIS AND ARCGIS
Sharanya Sarkar
 
PDF
CIFDAQ Market Insights for July 7th 2025
CIFDAQ
 
PDF
CIFDAQ Token Spotlight for 9th July 2025
CIFDAQ
 
PDF
Log-Based Anomaly Detection: Enhancing System Reliability with Machine Learning
Mohammed BEKKOUCHE
 
PPTX
Webinar: Introduction to LF Energy EVerest
DanBrown980551
 
PDF
The Builder’s Playbook - 2025 State of AI Report.pdf
jeroen339954
 
PDF
Presentation - Vibe Coding The Future of Tech
yanuarsinggih1
 
Using FME to Develop Self-Service CAD Applications for a Major UK Police Force
Safe Software
 
Blockchain Transactions Explained For Everyone
CIFDAQ
 
WooCommerce Workshop: Bring Your Laptop
Laura Hartwig
 
From Code to Challenge: Crafting Skill-Based Games That Engage and Reward
aiyshauae
 
UiPath Academic Alliance Educator Panels: Session 2 - Business Analyst Content
DianaGray10
 
Chris Elwell Woburn, MA - Passionate About IT Innovation
Chris Elwell Woburn, MA
 
HubSpot Main Hub: A Unified Growth Platform
Jaswinder Singh
 
LLMs.txt: Easily Control How AI Crawls Your Site
Keploy
 
From Sci-Fi to Reality: Exploring AI Evolution
Svetlana Meissner
 
"AI Transformation: Directions and Challenges", Pavlo Shaternik
Fwdays
 
Building Search Using OpenSearch: Limitations and Workarounds
Sease
 
OpenID AuthZEN - Analyst Briefing July 2025
David Brossard
 
CIFDAQ Weekly Market Wrap for 11th July 2025
CIFDAQ
 
COMPARISON OF RASTER ANALYSIS TOOLS OF QGIS AND ARCGIS
Sharanya Sarkar
 
CIFDAQ Market Insights for July 7th 2025
CIFDAQ
 
CIFDAQ Token Spotlight for 9th July 2025
CIFDAQ
 
Log-Based Anomaly Detection: Enhancing System Reliability with Machine Learning
Mohammed BEKKOUCHE
 
Webinar: Introduction to LF Energy EVerest
DanBrown980551
 
The Builder’s Playbook - 2025 State of AI Report.pdf
jeroen339954
 
Presentation - Vibe Coding The Future of Tech
yanuarsinggih1
 

Xml & Java

  • 1. FLASH #1 JAVA & XML PARSER
  • 2. Agenda ● SAX ● DOM ● STAX ● JAXB ● Conclusion
  • 3. SAX • Sequential reading of XML files. Can not be used to create XML documents. • SAX provides an Event-Driven XML Processing following the Push-Parsing Model. What this model means is that in SAX • Applications will register Listeners in the form of Handlers to the Parser and will get notified through Call-back methods. • Here the SAX Parser takes the control over Application thread by Pushing Events to the Application.
  • 4. EXAMPLE <?xml version="1.0"?> <howto> <topic> <title>Java</title> <url>http://www.rgagnon/javahowto.htm</url> </topic> <topic> <title>PowerBuilder</title> <url>http://www.rgagnon/pbhowto.htm</url> </topic> <topic> <title>Javascript</title> <url>http://www.rgagnon/jshowto.htm</url> </topic> <topic> <title>VBScript</title> <url>http://www.rgagnon/vbshowto.htm</url> </topic> </howto> Title: Java Url: http://www.rgagnon/javahowto.htm Title: PowerBuilder Url: http://www.rgagnon/pbhowto.htm Title: Javascript Url: http://www.rgagnon/jshowto.htm Title: VBScript Url: http://www.rgagnon/vbshowto.htm
  • 5. // jdk1.4.1 import java.io.*; import org.xml.sax.*; import org.xml.sax.helpers.*; // using SAX public class HowToListerSAX { class HowToHandler extends DefaultHandler { boolean title = false; boolean url = false; public void startElement(String nsURI, String strippedName, String tagName, Attributes attributes) throws SAXException { if (tagName.equalsIgnoreCase("title")) title = true; if (tagName.equalsIgnoreCase("url")) url = true; } public void characters(char[] ch, int start, int length) { if (title) { System.out.println("Title: " + new String(ch, start, length)); title = false; } else if (url) { System.out.println("Url: " + new String(ch, start,length)); url = false; } } } public void list( ) throws Exception { XMLReader parser = XMLReaderFactory.createXMLReader ("org.apache.crimson.parser.XMLReaderImpl"); parser.setContentHandler(new HowToHandler( )); parser.parse("howto.xml"); } public static void main(String[] args) throws Exception { new HowToListerSAX().list( ); } } I recommend not to use SAX.
  • 6. DOM ● The DOM is an interface that exposes an XML document as a tree structure comprised of nodes. ● The DOM allows you to programmatically navigate the tree and add, change and delete any of its elements.
  • 7. DOM / jdk1.4.1 import java.io.File; import javax.xml.parsers.*; import org.w3c.dom.*; // using DOM public class HowtoListerDOM { public static void main(String[] args) { File file = new File("howto.xml"); try { DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder(); Document doc = builder.parse(file); NodeList nodes = doc.getElementsByTagName("topic"); for (int i = 0; i < nodes.getLength(); i++) { Element element = (Element) nodes.item(i); NodeList title = element.getElementsByTagName("title"); Element line = (Element) title.item(0); System.out.println("Title: " + getCharacterDataFromElement(line)); NodeList url = element.getElementsByTagName("url"); line = (Element) url.item(0); System.out.println("Url: " + getCharacterDataFromElement(line)); } } catch (Exception e) { e.printStackTrace(); } } public static String getCharacterDataFromElement(Element e) { Node child = e.getFirstChild(); if (child instanceof CharacterData) { CharacterData cd = (CharacterData) child; return cd.getData(); } return "?"; } } I recommend not to use DOM.
  • 8. STAX ● Streaming API for XML, simply called StaX, is an API for reading and writing XML Documents. ● StaX is a Pull-Parsing model. Application can take the control over parsing the XML documents by pulling (taking) the events from the parser. ● The core StaX API falls into two categories and they are listed below. They are – Cursor API – Event Iterator API
  • 9. "Pull" vs. "Push" Style API SAX PARSER YOUR APP YOUR APP STAX PARSER Stax is cool if you need the control over the XML flow. Otherwise use JAXB.
  • 10. EXEMPLE <?xml version="1.0" encoding="UTF-8"?> <config> <mode>1</mode> <unit>900</unit> <current>1</current> <interactive>1</interactive> </config> import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.InputStream; import javax.xml.stream.XMLEventReader; import javax.xml.stream.XMLInputFactory; import javax.xml.stream.XMLStreamException; import javax.xml.stream.events.XMLEvent; public class ConfigFileStaX2 { private String configFile; public void setFile(String configFile) { this.configFile = configFile; } public static void main(String args[]) { ConfigFileStaX2 read = new ConfigFileStaX2(); read.setFile("config.xml"); read.readConfig(); } }
  • 11. public void readConfig() { try { // First create a new XMLInputFactory XMLInputFactory inputFactory = XMLInputFactory.newInstance(); // Setup a new eventReader InputStream in = new FileInputStream(configFile); XMLEventReader eventReader = inputFactory.createXMLEventReader(in); // Read the XML document while (eventReader.hasNext()) { XMLEvent event = eventReader.nextEvent(); if (event.isStartElement()) { if (event.asStartElement().getName().getLocalPart() == ("mode")) { event = eventReader.nextEvent(); System.out.println(event.asCharacters().getData()); continue; } if (event.asStartElement().getName().getLocalPart() == ("unit")) { event = eventReader.nextEvent(); System.out.println(event.asCharacters().getData()); continue; } if (event.asStartElement().getName().getLocalPart() == ("current")) { event = eventReader.nextEvent(); System.out.println(event.asCharacters().getData()); continue; } if (event.asStartElement().getName().getLocalPart() == ("interactive")) { event = eventReader.nextEvent(); System.out.println(event.asCharacters().getData()); continue; } } } } catch (Exception e) { e.printStackTrace(); } }
  • 12. PATTERN <?xml version="1.0" encoding="utf-8"?> <feed xmlns="http://www.w3.org/2005/Atom"> <title>Simple Atom Feed File</title> <subtitle>Using StAX to read feed files</subtitle> <link href="http://example.org/"/> <updated>2006-01-01T18:30:02Z</updated> <author> <name>Feed Author</name> <email>[email protected]</email> </author> <entry> <title>StAX parsing is simple</title> <link href="http://www.devx.com"/> <updated>2006-01-01T18:30:02Z</updated> <summary>Lean how to use StAX</summary> </entry> </feed> public interface ComponentParser { public void parseElement(XMLStreamReader staxXmlReader) throws XMLStreamException; }
  • 13. public class AuthorParser implements ComponentParser{ public void parse(XMLStreamReader staxXmlReader) throws XMLStreamException{ // read name StaxUtil.moveReaderToElement("name",staxXmlReader); String name = staxXmlReader.getElementText(); // read email StaxUtil.moveReaderToElement("email",staxXmlReader); String email = staxXmlReader.getElementText(); // Do something with author data... } } public class EntryParser implements ComponentParser { public void parse(XMLStreamReader staxXmlReader) throws XMLStreamException{ // read title StaxUtil.moveReaderToElement("title",staxXmlReader); String title = staxXmlReader.getElementText(); // read link attributes StaxUtil.moveReaderToElement("link",staxXmlReader); // read href attribute String linkHref = staxXmlReader.getAttributeValue(0); // read updated StaxUtil.moveReaderToElement("updated",staxXmlReader); String updated = staxXmlReader.getElementText(); // read title StaxUtil.moveReaderToElement("summary",staxXmlReader); String summary = staxXmlReader.getElementText(); // Do something with the data read from StAX.. } }
  • 14. public class StaxParser implements ComponentParser { private Map delegates; … public void parse(XMLStreamReader staxXmlReader) throws XMLStreamException{ for (int event = staxXmlReader.next(); event != XMLStreamConstants.END_DOCUMENT; event = staxXmlReader.next()) { if (event == XMLStreamConstants.START_ELEMENT) { String element = staxXmlReader.getLocalName(); // If a Component Parser is registered that can handle // this element delegate… if (delegates.containsKey(element)) { ComponentParser parser = (ComponentParser) delegates.get(element); parser.parse(staxXmlReader); } } } //rof } } InputStream in = this.getClass().getResourceAsStream("atom.xml"); XMLInputFactory factory = (XMLInputFactory) XMLInputFactory.newInstance(); XMLStreamReader staxXmlReader = (XMLStreamReader) factory.createXMLStreamReader(in); StaxParser parser = new StaxParser(); parser.registerParser("author",new AuthorParser()); parser.registerParser("entry",new EntryParser()); parser.parse(staxXmlReader);
  • 15. JAXB ● JAXB is a Java standard that defines how Java objects are converted to/from XML (specified using a standard set of mappings. ● JAXB defines a programmer API for reading and writing Java objects to / from XML documents and a service provider which / from from XML documents allows the selection of the JAXB implementation ● JAXB applies a lot of defaults thus making reading and writing of XML via Java very easy. I recommend to use JAXB (or Stax if you need more control).
  • 17. XML Parser API Feature Summary Feature StAX SAX DOM API Type Pull, streaming Push, streaming In memory tree Ease of Use High Medium High XPath Capability Not supported Not supported Supported CPU and Memory Good Good Varies Efficiency Read XML Supported Supported Supported Write XML Supported Not supported Supported
  • 18. NEXT ● JAXB + STAX – http://www.javarants.com/2006/04/30/simple- and-efficient-xml-parsing-using-jaxb-2-0/
  • 19. References ● http://www.j2ee.me/javaee/5/docs/tutorial/doc/bnb ● http://www.devx.com/Java/Article/30298/0/page/2 ● http://www.vogella.de/articles/JavaXML/article.htm ● http://tutorials.jenkov.com/java-xml/stax.html ● http://www.javarants.com/2006/04/30/simple- and-efficient-xml-parsing-using-jaxb-2-0/