SlideShare a Scribd company logo
1 of 19
Download to read offline
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

Jsp standard tag_library
Jsp standard tag_libraryJsp standard tag_library
Jsp standard tag_libraryKP Singh
 
Xml And JSON Java
Xml And JSON JavaXml And JSON Java
Xml And JSON JavaHenry Addo
 
Whitepaper To Study Filestream Option In Sql Server
Whitepaper To Study Filestream Option In Sql ServerWhitepaper To Study Filestream Option In Sql Server
Whitepaper To Study Filestream Option In Sql ServerShahzad
 
PostgreSQL- An Introduction
PostgreSQL- An IntroductionPostgreSQL- An Introduction
PostgreSQL- An IntroductionSmita Prasad
 
Xml processing in scala
Xml processing in scalaXml processing in scala
Xml processing in scalaKnoldus Inc.
 
04 data accesstechnologies
04 data accesstechnologies04 data accesstechnologies
04 data accesstechnologiesBat Programmer
 
Session06 handling xml data
Session06  handling xml dataSession06  handling xml data
Session06 handling xml datakendyhuu
 
Client Server Communication on iOS
Client Server Communication on iOSClient Server Communication on iOS
Client Server Communication on iOSMake School
 
Cursors, triggers, procedures
Cursors, triggers, proceduresCursors, triggers, procedures
Cursors, triggers, proceduresVaibhav Kathuria
 
Mule system properties
Mule system propertiesMule system properties
Mule system propertiesKarnam Karthik
 
Ado.net by Awais Majeed
Ado.net by Awais MajeedAdo.net by Awais Majeed
Ado.net by Awais MajeedAwais Majeed
 
oracle plsql training | oracle online training | oracle plsql demo | oracle p...
oracle plsql training | oracle online training | oracle plsql demo | oracle p...oracle plsql training | oracle online training | oracle plsql demo | oracle p...
oracle plsql training | oracle online training | oracle plsql demo | oracle p...Nancy Thomas
 

What's hot (20)

Jsp standard tag_library
Jsp standard tag_libraryJsp standard tag_library
Jsp standard tag_library
 
Xml And JSON Java
Xml And JSON JavaXml And JSON Java
Xml And JSON Java
 
Xslt mule
Xslt   muleXslt   mule
Xslt mule
 
Whitepaper To Study Filestream Option In Sql Server
Whitepaper To Study Filestream Option In Sql ServerWhitepaper To Study Filestream Option In Sql Server
Whitepaper To Study Filestream Option In Sql Server
 
PostgreSQL- An Introduction
PostgreSQL- An IntroductionPostgreSQL- An Introduction
PostgreSQL- An Introduction
 
Xml processing in scala
Xml processing in scalaXml processing in scala
Xml processing in scala
 
04 data accesstechnologies
04 data accesstechnologies04 data accesstechnologies
04 data accesstechnologies
 
Ajax
AjaxAjax
Ajax
 
spring-tutorial
spring-tutorialspring-tutorial
spring-tutorial
 
Session06 handling xml data
Session06  handling xml dataSession06  handling xml data
Session06 handling xml data
 
Client Server Communication on iOS
Client Server Communication on iOSClient Server Communication on iOS
Client Server Communication on iOS
 
Cursors, triggers, procedures
Cursors, triggers, proceduresCursors, triggers, procedures
Cursors, triggers, procedures
 
Core Java tutorial at Unit Nexus
Core Java tutorial at Unit NexusCore Java tutorial at Unit Nexus
Core Java tutorial at Unit Nexus
 
Mule properties
Mule propertiesMule properties
Mule properties
 
Mule system properties
Mule system propertiesMule system properties
Mule system properties
 
Simple Jdbc With Spring 2.5
Simple Jdbc With Spring 2.5Simple Jdbc With Spring 2.5
Simple Jdbc With Spring 2.5
 
Ado.net by Awais Majeed
Ado.net by Awais MajeedAdo.net by Awais Majeed
Ado.net by Awais Majeed
 
Jdbc ja
Jdbc jaJdbc ja
Jdbc ja
 
24sax
24sax24sax
24sax
 
oracle plsql training | oracle online training | oracle plsql demo | oracle p...
oracle plsql training | oracle online training | oracle plsql demo | oracle p...oracle plsql training | oracle online training | oracle plsql demo | oracle p...
oracle plsql training | oracle online training | oracle plsql demo | oracle p...
 

Viewers also liked

Viewers also liked (9)

XML Introduction
XML IntroductionXML Introduction
XML Introduction
 
Xml Presentation-3
Xml Presentation-3Xml Presentation-3
Xml Presentation-3
 
Entity beans in java
Entity beans in javaEntity beans in java
Entity beans in java
 
Introduction to EJB
Introduction to EJBIntroduction to EJB
Introduction to EJB
 
Xml
XmlXml
Xml
 
EJB .
EJB .EJB .
EJB .
 
Introduction to xml
Introduction to xmlIntroduction to xml
Introduction to xml
 
Introduction to XML
Introduction to XMLIntroduction to XML
Introduction to XML
 
Enterprise JavaBeans(EJB)
Enterprise JavaBeans(EJB)Enterprise JavaBeans(EJB)
Enterprise JavaBeans(EJB)
 

Similar to Xml & Java

Struts database access
Struts database accessStruts database access
Struts database accessAbass Ndiaye
 
Introducing Struts 2
Introducing Struts 2Introducing Struts 2
Introducing Struts 2wiradikusuma
 
Advance Java Programs skeleton
Advance Java Programs skeletonAdvance Java Programs skeleton
Advance Java Programs skeletonIram Ramrajkar
 
比XML更好用的Java Annotation
比XML更好用的Java Annotation比XML更好用的Java Annotation
比XML更好用的Java Annotationjavatwo2011
 
Tomcat连接池配置方法V2.1
Tomcat连接池配置方法V2.1Tomcat连接池配置方法V2.1
Tomcat连接池配置方法V2.1Zianed Hou
 
SAX, DOM & JDOM parsers for beginners
SAX, DOM & JDOM parsers for beginnersSAX, DOM & JDOM parsers for beginners
SAX, DOM & JDOM parsers for beginnersHicham QAISSI
 
jQuery for beginners
jQuery for beginnersjQuery for beginners
jQuery for beginnersDivakar Gu
 
jQuery - Chapter 5 - Ajax
jQuery - Chapter 5 -  AjaxjQuery - Chapter 5 -  Ajax
jQuery - Chapter 5 - AjaxWebStackAcademy
 
Apache Utilities At Work V5
Apache Utilities At Work   V5Apache Utilities At Work   V5
Apache Utilities At Work V5Tom Marrs
 
Java Programming Must implement a storage manager that main.pdf
Java Programming Must implement a storage manager that main.pdfJava Programming Must implement a storage manager that main.pdf
Java Programming Must implement a storage manager that main.pdfadinathassociates
 
IQPC Canada XML 2001: How to Use XML Parsing to Enhance Electronic Communication
IQPC Canada XML 2001: How to Use XML Parsing to Enhance Electronic CommunicationIQPC Canada XML 2001: How to Use XML Parsing to Enhance Electronic Communication
IQPC Canada XML 2001: How to Use XML Parsing to Enhance Electronic CommunicationTed Leung
 
Web CrawlersrcedusmulylecrawlerController.javaWeb Crawler.docx
Web CrawlersrcedusmulylecrawlerController.javaWeb Crawler.docxWeb CrawlersrcedusmulylecrawlerController.javaWeb Crawler.docx
Web CrawlersrcedusmulylecrawlerController.javaWeb Crawler.docxcelenarouzie
 
Selenium Webdriver with data driven framework
Selenium Webdriver with data driven frameworkSelenium Webdriver with data driven framework
Selenium Webdriver with data driven frameworkDavid Rajah Selvaraj
 
Overview of RESTful web services
Overview of RESTful web servicesOverview of RESTful web services
Overview of RESTful web servicesnbuddharaju
 
Jersey framework
Jersey frameworkJersey framework
Jersey frameworkknight1128
 

Similar to Xml & Java (20)

Stax parser
Stax parserStax parser
Stax parser
 
Struts database access
Struts database accessStruts database access
Struts database access
 
Java XML Parsing
Java XML ParsingJava XML Parsing
Java XML Parsing
 
Introducing Struts 2
Introducing Struts 2Introducing Struts 2
Introducing Struts 2
 
Advance Java Programs skeleton
Advance Java Programs skeletonAdvance Java Programs skeleton
Advance Java Programs skeleton
 
比XML更好用的Java Annotation
比XML更好用的Java Annotation比XML更好用的Java Annotation
比XML更好用的Java Annotation
 
Tomcat连接池配置方法V2.1
Tomcat连接池配置方法V2.1Tomcat连接池配置方法V2.1
Tomcat连接池配置方法V2.1
 
SAX, DOM & JDOM parsers for beginners
SAX, DOM & JDOM parsers for beginnersSAX, DOM & JDOM parsers for beginners
SAX, DOM & JDOM parsers for beginners
 
jQuery for beginners
jQuery for beginnersjQuery for beginners
jQuery for beginners
 
jQuery - Chapter 5 - Ajax
jQuery - Chapter 5 -  AjaxjQuery - Chapter 5 -  Ajax
jQuery - Chapter 5 - Ajax
 
Apache Utilities At Work V5
Apache Utilities At Work   V5Apache Utilities At Work   V5
Apache Utilities At Work V5
 
Ejb3 Dan Hinojosa
Ejb3 Dan HinojosaEjb3 Dan Hinojosa
Ejb3 Dan Hinojosa
 
Java Programming Must implement a storage manager that main.pdf
Java Programming Must implement a storage manager that main.pdfJava Programming Must implement a storage manager that main.pdf
Java Programming Must implement a storage manager that main.pdf
 
IQPC Canada XML 2001: How to Use XML Parsing to Enhance Electronic Communication
IQPC Canada XML 2001: How to Use XML Parsing to Enhance Electronic CommunicationIQPC Canada XML 2001: How to Use XML Parsing to Enhance Electronic Communication
IQPC Canada XML 2001: How to Use XML Parsing to Enhance Electronic Communication
 
Web CrawlersrcedusmulylecrawlerController.javaWeb Crawler.docx
Web CrawlersrcedusmulylecrawlerController.javaWeb Crawler.docxWeb CrawlersrcedusmulylecrawlerController.javaWeb Crawler.docx
Web CrawlersrcedusmulylecrawlerController.javaWeb Crawler.docx
 
Selenium Webdriver with data driven framework
Selenium Webdriver with data driven frameworkSelenium Webdriver with data driven framework
Selenium Webdriver with data driven framework
 
Overview of RESTful web services
Overview of RESTful web servicesOverview of RESTful web services
Overview of RESTful web services
 
JavaServer Pages
JavaServer PagesJavaServer Pages
JavaServer Pages
 
Ajax
AjaxAjax
Ajax
 
Jersey framework
Jersey frameworkJersey framework
Jersey framework
 

More from Slim Ouertani

More from Slim Ouertani (18)

merged_document_3
merged_document_3merged_document_3
merged_document_3
 
Microservice architecture
Microservice architectureMicroservice architecture
Microservice architecture
 
MongoDb java
MongoDb javaMongoDb java
MongoDb java
 
OCJP
OCJPOCJP
OCJP
 
Effectuation: entrepreneurship for all
Effectuation: entrepreneurship for all Effectuation: entrepreneurship for all
Effectuation: entrepreneurship for all
 
Spring
SpringSpring
Spring
 
Principles of Reactive Programming
Principles of Reactive ProgrammingPrinciples of Reactive Programming
Principles of Reactive Programming
 
Functional Programming Principles in Scala
Functional Programming Principles in ScalaFunctional Programming Principles in Scala
Functional Programming Principles in Scala
 
Introduction to Cmmi for development
Introduction to Cmmi for development Introduction to Cmmi for development
Introduction to Cmmi for development
 
MongoDb java
MongoDb javaMongoDb java
MongoDb java
 
DBA MongoDb
DBA MongoDbDBA MongoDb
DBA MongoDb
 
SOA Trainer
SOA TrainerSOA Trainer
SOA Trainer
 
SOA Professional
SOA ProfessionalSOA Professional
SOA Professional
 
SOA Architect
SOA ArchitectSOA Architect
SOA Architect
 
PMP Score
PMP ScorePMP Score
PMP Score
 
PMP
PMPPMP
PMP
 
Programmation fonctionnelle Scala
Programmation fonctionnelle ScalaProgrammation fonctionnelle Scala
Programmation fonctionnelle Scala
 
Singleton Sum
Singleton SumSingleton Sum
Singleton Sum
 

Recently uploaded

Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountPuma Security, LLC
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024Results
 
What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?Antenna Manufacturer Coco
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?Igalia
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)wesley chun
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking MenDelhi Call girls
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxMalak Abu Hammad
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Scriptwesley chun
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking MenDelhi Call girls
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEarley Information Science
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...apidays
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024The Digital Insurer
 
Advantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessAdvantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessPixlogix Infotech
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)Gabriella Davis
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationSafe Software
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxKatpro Technologies
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Enterprise Knowledge
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CVKhem
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Servicegiselly40
 

Recently uploaded (20)

Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path Mount
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024
 
What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptx
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024
 
Advantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessAdvantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your Business
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CV
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
 

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>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; }
  • 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/