Java and J2EE Tutorials, Jsp and Servlet Tutorials, Spring MVC, Solr, XML, JSON Examples, Hibernate & Struts 2 Hello World projects



Friday, 7 June 2013

SAX parser for Xml - How to read xml file in Java using SAX parser

SAX parser is the most commonly used xml parser in Java after DOM, unlike DOM Sax does not loads the XML into memory before parsing it, nor it creates any type of object from XML. SAX is a better choice to parse xml's with large size. SAX uses some callback methods to parse and read the xml accordingly. It uses three callback methods listed below :

startElement() : Every time a SAX parser gets a opening tag '<', it calls startElement() and process the xml according to the code written in startElement().

endElement(): Every time a SAX parser gets a closing tag '>', it calls endElement() and process the xml according to the code written in endElement().

character(): Every time a SAX parser gets a simple character string, it calls character() method and the xml according to the code written in startElement().

The three methods explained above are responsible to parse the xml in SAX parser, developer use the methods as events and can write parsing and extraction code accordingly.

In today's discussion we will come across a sample project to simplify 'how to read an xml in java using sax parser' and 'how to use sax for xml parsing'.

Sample Project

Here is the overall project structure for today's discussion, 'xmlToRead' folder contains xml that we are going to read and display the output on console. 'ReadXml.java ' contains the parsing code in java to read xml using sax.



Object XML to parse

Here is the sample xml document that we are going to parse and write the content on console.
<?xml version="1.0" encoding="UTF-8"?>
<school>
 <student id="1">
  <firstname>ankush</firstname>
  <lastname>thakur</lastname>
  <email>beingjavaguy.gmail.com</email>
  <phone>7678767656</phone>
 </student>
 <student id="2">
  <firstname>aarti</firstname>
  <lastname>gupta</lastname>
  <email>aartigupta.gmail.com</email>
  <phone>9876546545</phone>
 </student>
</school>


src\com\beingjavaguys\core\ReadXml.java

This class shows actual implementation of sax parser in java, see the code below to understand how to use sax in xml parser:
package com.beingjavaguys.core;

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 ReadXml extends DefaultHandler{
 
public void getXml(){
  try {
   // obtain and configure a SAX based parser
   SAXParserFactory saxParserFactory = SAXParserFactory.newInstance();

   // obtain object for SAX parser
   SAXParser saxParser = saxParserFactory.newSAXParser();

   // default handler for SAX handler class
   // all three methods are written in handler's body
   DefaultHandler defaultHandler = new DefaultHandler(){
    
    String firstNameTag="close";
    String lastNameTag="close";
    String emailTag="close";
    String phoneTag="close";
    
    // this method is called every time the parser gets an open tag '<'
    // identifies which tag is being open at time by assigning an open flag
    public void startElement(String uri, String localName, String qName,
      Attributes attributes) throws SAXException {
   
     if (qName.equalsIgnoreCase("FIRSTNAME")) {
      firstNameTag = "open";
     }
     if (qName.equalsIgnoreCase("LASTNAME")) {
      lastNameTag = "open";
     }
     if (qName.equalsIgnoreCase("EMAIL")) {
      emailTag = "open";
     }
     if (qName.equalsIgnoreCase("PHONE")) {
      phoneTag = "open";
     }
    }

    // prints data stored in between '<' and '>' tags
    public void characters(char ch[], int start, int length)
      throws SAXException {
     
     if (firstNameTag.equals("open")) {
      System.out.println("First Name : " + new String(ch, start, length));
     }
     if (lastNameTag.equals("open")) {
      System.out.println("Last Name : " + new String(ch, start, length));
     }
     if (emailTag.equals("open")) {
      System.out.println("Email : " + new String(ch, start, length));
     }
     if (phoneTag.equals("open")) {
      System.out.println("Phone : " + new String(ch, start, length));
     }
    }

    // calls by the parser whenever '>' end tag is found in xml 
    // makes tags flag to 'close'
    public void endElement(String uri, String localName, String qName)
      throws SAXException {
     
     if (qName.equalsIgnoreCase("firstName")) {
      firstNameTag = "close";
     }
     if (qName.equalsIgnoreCase("lastName")) {
      lastNameTag = "close";
     }
     if (qName.equalsIgnoreCase("email")) {
      emailTag = "close";
     }
     if (qName.equalsIgnoreCase("phone")) {
      phoneTag = "close";
     }
    }
   };
   
   // parse the XML specified in the given path and uses supplied
   // handler to parse the document
   // this calls startElement(), endElement() and character() methods
   // accordingly
   saxParser.parse("xmlToRead/student.xml", defaultHandler);
  } catch (Exception e) {
   e.printStackTrace();
  }
 }
}



Implementation class code

This is a simple implementation class to see the things working.
package com.beingjavaguys.core;

public class SaxParserImplementation {
  public static void main(String args[]){
   ReadXml readXml = new ReadXml();
   readXml.getXml();
  }
}

Output

This is the output that we will get on console after reading the specified xml file.



In this particular blog we cam across 'How to read xml in java using sax parser' and 'how to use sax for xml parsing'. In upcoming blogs we will come across more about more xml parser in java and their implementation. Read more about XML & JSON under DOM & JDOM2 & XML parser in Java JSON, and JAXB - Marshalling & Unmarshalling in Java categories.








Thanks for reading !
Being Java Guys Team

Download "SAX Parser in Java Example Project" from "SkyDrive"





11 comments:

  1. Sax can create XML output too
    ^_^

    ReplyDelete
    Replies
    1. Stephan do u have any link or tutorial to create output using sax method. Even i have read that Sax can create XML output

      Delete
  2. Thanks guys. Nice work.
    I have a question though..
    How to read the student id as well..??

    ReplyDelete
  3. does it works even if the tag hasn't been yet writtern?

    ReplyDelete
  4. thanks guys i have been looking around for simple explanation not code snippet ,totally understand this now ,thanks a lot.

    ReplyDelete
  5. How do i parse a dynamic xml file? i know only its element.

    ReplyDelete
  6. hi..

    How do i read the value of Student ID as well

    ReplyDelete
    Replies
    1. pls write this in startElemen method...


      if (qName.equalsIgnoreCase("student")) {
      System.out.println(attributes.getLocalName(0) +"="+ attributes.getValue(0));
      }

      Delete
    2. JAXB in JAVA - Convert Java to Xml and Xml to Java---> 404 page not found.

      Delete
  7. Could u guide me
    1) I want to pass these values to in a method
    2) I want to store the values in an array

    How to do this

    ReplyDelete

Like Us on Facebook


Like Us On Google+



Contact

Email: neel4soft@gmail.com
Skype: neel4soft