Core Java

Parsing XML using DOM, SAX and StAX Parser in Java

I happen to read through a chapter on XML parsing and building APIs in Java. And I tried out the different parser available on a sample XML. Then I thought of sharing it on my blog so that I can have a reference to the code as well as a reference for anyone reading this. In this post I parse the same XML in different parsers to perform the same operation of populating the XML content into objects and then adding the objects to a list.
The sample XML considered in the examples is:

<employees>
  <employee id="111">
    <firstName>Rakesh</firstName>
    <lastName>Mishra</lastName>
    <location>Bangalore</location>
  </employee>
  <employee id="112">
    <firstName>John</firstName>
    <lastName>Davis</lastName>
    <location>Chennai</location>
  </employee>
  <employee id="113">
    <firstName>Rajesh</firstName>
    <lastName>Sharma</lastName>
    <location>Pune</location>
  </employee>
</employees>

And the obejct into which the XML content is to be extracted is defined as below:

class Employee{
  String id;
  String firstName;
  String lastName;
  String location;

  @Override
  public String toString() {
    return firstName+" "+lastName+"("+id+")"+location;
  }
}

There are 3 main parsers for which I have given sample code:

Using DOM Parser

I am making use of the DOM parser implementation that comes with the JDK and in my example I am using JDK 7. The DOM Parser loads the complete XML content into a Tree structure. And we iterate through the Node and NodeList to get the content of the XML. The code for XML parsing using DOM parser is given below.

public class DOMParserDemo {

  public static void main(String[] args) throws Exception {
    //Get the DOM Builder Factory
    DocumentBuilderFactory factory = 
        DocumentBuilderFactory.newInstance();

    //Get the DOM Builder
    DocumentBuilder builder = factory.newDocumentBuilder();

    //Load and Parse the XML document
    //document contains the complete XML as a Tree.
    Document document = 
      builder.parse(
        ClassLoader.getSystemResourceAsStream("xml/employee.xml"));

    List<Employee> empList = new ArrayList<>();

    //Iterating through the nodes and extracting the data.
    NodeList nodeList = document.getDocumentElement().getChildNodes();

    for (int i = 0; i < nodeList.getLength(); i++) {

      //We have encountered an <employee> tag.
      Node node = nodeList.item(i);
      if (node instanceof Element) {
        Employee emp = new Employee();
        emp.id = node.getAttributes().
            getNamedItem("id").getNodeValue();

        NodeList childNodes = node.getChildNodes();
        for (int j = 0; j < childNodes.getLength(); j++) {
          Node cNode = childNodes.item(j);

          //Identifying the child tag of employee encountered. 
          if (cNode instanceof Element) {
            String content = cNode.getLastChild().
                getTextContent().trim();
            switch (cNode.getNodeName()) {
              case "firstName":
                emp.firstName = content;
                break;
              case "lastName":
                emp.lastName = content;
                break;
              case "location":
                emp.location = content;
                break;
            }
          }
        }
        empList.add(emp);
      }

    }

    //Printing the Employee list populated.
    for (Employee emp : empList) {
      System.out.println(emp);
    }

  }
}

class Employee{
  String id;
  String firstName;
  String lastName;
  String location;

  @Override
  public String toString() {
    return firstName+" "+lastName+"("+id+")"+location;
  }
}

The output for the above will be:

Rakesh Mishra(111)Bangalore
John Davis(112)Chennai
Rajesh Sharma(113)Pune

Using SAX Parser

SAX Parser is different from the DOM Parser where SAX parser doesn’t load the complete XML into the memory, instead it parses the XML line by line triggering different events as and when it encounters different elements like: opening tag, closing tag, character data, comments and so on. This is the reason why SAX Parser is called an event based parser.

Along with the XML source file, we also register a handler which extends the DefaultHandler class. The DefaultHandler class provides different callbacks out of which we would be interested in:

  • startElement() – triggers this event when the start of the tag is encountered.
  • endElement() – triggers this event when the end of the tag is encountered.
  • characters() – triggers this event when it encounters some text data.

The code for parsing the XML using SAX Parser is given below:

import java.util.ArrayList;
import java.util.List;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

public class SAXParserDemo {

  public static void main(String[] args) throws Exception {
    SAXParserFactory parserFactor = SAXParserFactory.newInstance();
    SAXParser parser = parserFactor.newSAXParser();
    SAXHandler handler = new SAXHandler();
    parser.parse(ClassLoader.getSystemResourceAsStream("xml/employee.xml"), 
                 handler);

    //Printing the list of employees obtained from XML
    for ( Employee emp : handler.empList){
      System.out.println(emp);
    }
  }
}
/**
 * The Handler for SAX Events.
 */
class SAXHandler extends DefaultHandler {

  List<Employee> empList = new ArrayList<>();
  Employee emp = null;
  String content = null;
  @Override
  //Triggered when the start of tag is found.
  public void startElement(String uri, String localName, 
                           String qName, Attributes attributes) 
                           throws SAXException {

    switch(qName){
      //Create a new Employee object when the start tag is found
      case "employee":
        emp = new Employee();
        emp.id = attributes.getValue("id");
        break;
    }
  }

  @Override
  public void endElement(String uri, String localName, 
                         String qName) throws SAXException {
   switch(qName){
     //Add the employee to list once end tag is found
     case "employee":
       empList.add(emp);       
       break;
     //For all other end tags the employee has to be updated.
     case "firstName":
       emp.firstName = content;
       break;
     case "lastName":
       emp.lastName = content;
       break;
     case "location":
       emp.location = content;
       break;
   }
  }

  @Override
  public void characters(char[] ch, int start, int length) 
          throws SAXException {
    content = String.copyValueOf(ch, start, length).trim();
  }

}

class Employee {

  String id;
  String firstName;
  String lastName;
  String location;

  @Override
  public String toString() {
    return firstName + " " + lastName + "(" + id + ")" + location;
  }
}

The output for the above would be:

Rakesh Mishra(111)Bangalore
John Davis(112)Chennai
Rajesh Sharma(113)Pune

Using StAX Parser

StAX stands for Streaming API for XML and StAX Parser is different from DOM in the same way SAX Parser is. StAX parser is also in a subtle way different from SAX parser.

  • The SAX Parser pushes the data but StAX parser pulls the required data from the XML.
  • The StAX parser maintains a cursor at the current position in the document allows to extract the content available at the cursor whereas SAX parser issues events as and when certain data is encountered.

XMLInputFactory and XMLStreamReader are the two class which can be used to load an XML file. And as we read through the XML file using XMLStreamReader, events are generated in the form of integer values and these are then compared with the constants in XMLStreamConstants. The below code shows how to parse XML using StAX parser:

import java.util.ArrayList;
import java.util.List;
import javax.xml.stream.XMLInputFactory;
import javax.xml.stream.XMLStreamConstants;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamReader;

public class StaxParserDemo {
  public static void main(String[] args) throws XMLStreamException {
    List<Employee> empList = null;
    Employee currEmp = null;
    String tagContent = null;
    XMLInputFactory factory = XMLInputFactory.newInstance();
    XMLStreamReader reader = 
        factory.createXMLStreamReader(
        ClassLoader.getSystemResourceAsStream("xml/employee.xml"));

    while(reader.hasNext()){
      int event = reader.next();

      switch(event){
        case XMLStreamConstants.START_ELEMENT: 
          if ("employee".equals(reader.getLocalName())){
            currEmp = new Employee();
            currEmp.id = reader.getAttributeValue(0);
          }
          if("employees".equals(reader.getLocalName())){
            empList = new ArrayList<>();
          }
          break;

        case XMLStreamConstants.CHARACTERS:
          tagContent = reader.getText().trim();
          break;

        case XMLStreamConstants.END_ELEMENT:
          switch(reader.getLocalName()){
            case "employee":
              empList.add(currEmp);
              break;
            case "firstName":
              currEmp.firstName = tagContent;
              break;
            case "lastName":
              currEmp.lastName = tagContent;
              break;
            case "location":
              currEmp.location = tagContent;
              break;
          }
          break;

        case XMLStreamConstants.START_DOCUMENT:
          empList = new ArrayList<>();
          break;
      }

    }

    //Print the employee list populated from XML
    for ( Employee emp : empList){
      System.out.println(emp);
    }

  }
}

class Employee{
  String id;
  String firstName;
  String lastName;
  String location;

  @Override
  public String toString(){
    return firstName+" "+lastName+"("+id+") "+location;
  }
}

The output for the above is:

Rakesh Mishra(111) Bangalore
John Davis(112) Chennai
Rajesh Sharma(113) Pune

With this I have covered parsing the same XML document and performing the same task of populating the list of Employee objects using all the three parsers namely:

Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

30 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Neo Lite
Neo Lite
11 years ago

Thanks for sharing.

Neo
http://javawithneo.blogpost.com

Sam
Sam
10 years ago
Reply to  Neo Lite

+1

Noam
Noam
11 years ago

Thanks for sharing!

Amirtharaj
Amirtharaj
11 years ago

good tutorial

Padma
Padma
11 years ago

Indeed best work …Thanks for sharing your experience .

Test Developer
Test Developer
11 years ago

Could you please share which one was the fastest one?

Santosh
Santosh
11 years ago

Neat and clear demonstration. Thanks for sharing it.

Pranav
Pranav
11 years ago

Thanks for sharing. Keep up the good work.

Mak
Mak
11 years ago

Thanks!!!!

regu
regu
11 years ago

Thanks.

asd
asd
10 years ago

Thanks for sharing. Great tutorial. I am C# developer but this was very useful :)

vin
vin
10 years ago

In stax parser.. the second switch case is using string in condition which is not allowing me to do so. can you please look into it ?

Hayden
Hayden
10 years ago
Reply to  vin

Update JDK to >= 7, until JDK7 you couldn’t use Strings in switch statements.

OM
OM
10 years ago

i m getting a error in the switch case condition.switch (qName),,Cannot switch on a value of type String. Only convertible int values or enum constants are permitted

can u pls suggest me why i m getting this error and how come i can fix this.

Jasvir
Jasvir
9 years ago
Reply to  OM

Switch on String types are allowed only in JDK 8 and above.

Narayana Reddy
Narayana Reddy
10 years ago

Very good explanation and example.

Rafael
Rafael
10 years ago

Amazing example! Thank you a million for sharing.

Chris Noffsinger
Chris Noffsinger
10 years ago

Awesome. Thank you.

Jim
Jim
10 years ago

My path to my xml file is a Windows path, such as this: C:\Data\Documents\Separated Byspace\Comments.xml . Prior to calling….. XMLStreamReader reader = factory.createXMLStreamReader(ClassLoader.getSystemResourceAsStream(incoming)); ….I surround incoming with double quotes, like this: incoming = “\”” + file.getCanonicalPath() + “\””; When i try to open the stream I get a java.lang.NullPointerException – at least, I suspect it is when I try to open the stream. Here is the java dump: javax.xml.stream.XMLStreamException: java.net.MalformedURLException at com.sun.org.apache.xerces.internal.impl.XMLStreamReaderImpl.setInputSource(Unknown Source) at com.sun.org.apache.xerces.internal.impl.XMLStreamReaderImpl.(Unknown Source) at com.sun.xml.internal.stream.XMLInputFactoryImpl.getXMLStreamReaderImpl(Unknown Source) at com.sun.xml.internal.stream.XMLInputFactoryImpl.createXMLStreamReader(Unknown Source) at indexXML.parseComments(indexXML.java:86) at indexXML.recurseDirectory(indexXML.java:59) at indexXML.recurseDirectory(indexXML.java:48) at indexXML.recurseDirectory(indexXML.java:48) at indexXML.main(indexXML.java:32) Caused by: java.net.MalformedURLException at java.net.URL.(Unknown Source) at java.net.URL.(Unknown… Read more »

Jasvir
Jasvir
9 years ago
Reply to  Jim

ClassLoader.getSystemResourceAsStream(incoming) must be returning null;

If you’re using maven project, create a source folder (that goes by the name src/main/resources) using eclipse.
You should be go to go

Ranjana A
Ranjana A
10 years ago

Simple And clear.Thanks !!

Andrei
Andrei
9 years ago

DOM parser on line:
37 String content = cNode.getLastChild().getTextContent().trim();

I would check for nulls (empty nodes):
String content = cNode.getLastChild()==null ? “” : cNode.getLastChild().getTextContent().trim();

Thanks for the sample code.

Senthil
Senthil
9 years ago

simple and very good one.. especially to understand the push and pull differences between SAX and StAX!

G Chandrasekhar
G Chandrasekhar
9 years ago

Hi,

This is very nice, and i am new to xml parsers, i gone through so many sites, but i didnt get clarity, which parser is mostly used in our real time application? can u tell me about that ?

Back to top button