Java Read XML using SAX Parser

SAX Parser or, Simple API for XML, has been around for many years and was originally a development led by David Megginson before the turn of the millennium. In those days, you had to download the Java version of SAX from David’s personal website. This developed into the SAX Project before finally being added to Java Standard Edition 1.4.

SAX is a streaming interface for XML, which means that applications receive event notifications about the XML document being processed an element, and attribute, at a time in sequential order starting at the top of the document and ending with the closing of the ROOT element. This means that its extremely efficient at processing XML in linear time without placing too many demands upon system memory.

1. Setup

This XML file contains xml attributes also along with child elements.

  <user id="100">
  <user id="101">
  <user id="102">

2. Create Java POJO

The User class has simple attributes to store the information read from the XML file.

public class User {

  private int id;
  private String firstName;
  private String lastName;

  //Setters, getters

3. SAX Event Handler

The event handler receives the events for each event during the read operation through method callbacks to the following functions:

  • startElement()
  • endElement()

Inside the functions, we can use if-statement to know which element is currently being processed and then we can extract the required information.

import java.util.ArrayList;
import java.util.Stack;

import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

public class UserParserHandler extends DefaultHandler {

  //This is the list which shall be populated while parsing the XML.
  private ArrayList userList = new ArrayList();

  //As we read any XML element we will push that in this stack
  private Stack elementStack = new Stack();

  //As we complete one user block in XML, we will push the User instance in userList
  private Stack objectStack = new Stack();

  public void startDocument() throws SAXException {
    //System.out.println("start of the document   : ");

  public void endDocument() throws SAXException {
    //System.out.println("end of the document document     : ");

  public void startElement(String uri, String localName, String qName, Attributes attributes)
      throws SAXException {
    //Push it in element stack

    //If this is start of 'user' element then prepare a new User instance and push it in object stack
    if ("user".equals(qName)) {
      //New User instance
      User user = new User();

      //Set all required attributes in any XML element here itself
      if (attributes != null && attributes.getLength() == 1) {

  public void endElement(String uri, String localName, String qName) throws SAXException {
    //Remove last added  element

    //User instance has been constructed so pop it from object stack and push in userList
    if ("user".equals(qName)) {
      User object = (User) this.objectStack.pop();

   * This will be called everytime parser encounter a value node
  public void characters(char[] ch, int start, int length) throws SAXException {
    String value = new String(ch, start, length).trim();

    if (value.length() == 0) {
      return; // ignore white space

    //handle the value based on to which element it belongs
    if ("firstName".equals(currentElement())) {
      User user = (User) this.objectStack.peek();
    } else if ("lastName".equals(currentElement())) {
      User user = (User) this.objectStack.peek();

   * Utility method for getting the current element in processing
  private String currentElement() {
    return (String) this.elementStack.peek();

  //Accessor for userList object
  public ArrayList getUsers() {
    return userList;

4. Reading the XML File

The handler class is set as the content handler for the XMLReader using the method reader.setContentHandler(handler). The reader takes the input XML in various forms, accepted as an argument to InputSource constructor. Finally, we use reader.parse() method to read the XML content.

import java.util.ArrayList;

import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;
import org.xml.sax.helpers.XMLReaderFactory;

public class UserParser {

  public ArrayList parseXml(InputStream in) {
    //Create an empty link of users initially
    ArrayList<User> users = new ArrayList<>();
    try {
      //Create default handler instance
      UserParserHandler handler = new UserParserHandler();

      //Create parser from factory
      XMLReader reader = XMLReaderFactory.createXMLReader();

      //Register handler with parser

      //Create an input source from the XML input stream
      InputSource source = new InputSource(in);

      //parse the document

      //populate the parsed users list in above created empty list; You can return from here also.
      users = handler.getUsers();

    } catch (SAXException e) {
    } catch (IOException e) {
    } finally {

    return users;

5. Demo

Let us write some code to test whether our handler is actually working.

import java.util.ArrayList;

public class SaxParserDemo {

  public static void main(String[] args) throws FileNotFoundException {
    //Locate the file
    File xmlFile = new File("D:/temp/sample.xml");

    //Create the parser instance
    UserParser parser = new UserParser();

    //Parse the file
    ArrayList<User> users = parser.parseXml(new FileInputStream(xmlFile));

    //Verify the result

Program output.

[100:Tom:Hanks, 101:Lokesh:Gupta, 102:HowToDo:InJava]

Happy Learning !!

Sourcecode in Github


Notify of
Most Voted
Newest Oldest
Inline Feedbacks
View all comments

About Us

HowToDoInJava provides tutorials and how-to guides on Java and related technologies.

It also shares the best practices, algorithms & solutions and frequently asked interview questions.