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

"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek SchlawackFwdays
 
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxLoriGlavin3
 
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc
 
Story boards and shot lists for my a level piece
Story boards and shot lists for my a level pieceStory boards and shot lists for my a level piece
Story boards and shot lists for my a level piececharlottematthew16
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsSergiu Bodiu
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupFlorian Wilhelm
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsMark Billinghurst
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Commit University
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Mattias Andersson
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLScyllaDB
 
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdfHyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdfPrecisely
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfAddepto
 
Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Enterprise Knowledge
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsRizwan Syed
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii SoldatenkoFwdays
 
DSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningDSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningLars Bell
 
Artificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxArtificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxhariprasad279825
 

Recently uploaded (20)

"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
 
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
 
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
 
Story boards and shot lists for my a level piece
Story boards and shot lists for my a level pieceStory boards and shot lists for my a level piece
Story boards and shot lists for my a level piece
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platforms
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project Setup
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR Systems
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?
 
DMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special EditionDMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special Edition
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQL
 
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdfHyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdf
 
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptxE-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
 
Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL Certs
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko
 
DSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningDSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine Tuning
 
Artificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxArtificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptx
 

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/