Java SAX Tutorial

Java SAX tutorial shows how to use Java SAX API to read XML documents.


SAX (Simple API for XML) is an event-driven algorithm for parsing XML documents. SAX is an alternative to the Document Object Model (DOM). Where the DOM reads the whole document to operate on XML, SAX parsers read XML node by node, issuing parsing events while making a step through the input stream. SAX processes documents state-independently (the handling of an element does not depend on the elements that came before). SAX parsers are read-only.

SAX parsers are faster and require less memory. On the other hand, DOM is easier to use and there are tasks, such as sorting elements, rearranging elements or looking up elements, that are faster with DOM.

A SAX parser comes with JDK, so there is no need to download a dependency.

Development Process Steps

  1. Input sax_users.xml File(XML file we will read)
  2. Create SAX Parser Handler class extending DefaultHandler class
  3. Create User class (populate XML data into User object)
  4. Program to Read XML File in Java using Java DOM Parser

1. Input users.xml File(XML file we will read)

Here is the XML file that will be read in this program.
<?xml version="1.0" encoding="UTF-8"?>
 <User id= "1">
 <User id= "2">
 <User id= "3">

2. Create SAX Parser Handler class extending DefaultHandler class

Let’s create our own SAX Parser Handler class extending DefaultHandler class.
package net.javaguides.javaxmlparser.sax;

import java.util.ArrayList;
import java.util.List;

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

public class UserHandler extends DefaultHandler {

    private boolean hasFirstName = false;
    private boolean hasLastName = false;
    private boolean hasAge = false;
    private boolean hasGender = false;

    // List to hold Users object
    private List < User > userList = null;
    private User user = null;

    // getter method for userloyee list
    public List < User > getEmpList() {
        return userList;

    public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {

        if (qName.equalsIgnoreCase("User")) {
            // create a new User and put it in Map
            String id = attributes.getValue("id");
            // initialize User object and set id attribute
            user = new User();
            // initialize list
            if (userList == null)
                userList = new ArrayList < > ();
        } else if (qName.equalsIgnoreCase("firstName")) {
            // set boolean values for fields, will be used in setting User variables
            hasFirstName = true;
        } else if (qName.equalsIgnoreCase("age")) {
            hasAge = true;
        } else if (qName.equalsIgnoreCase("gender")) {
            hasGender = true;
        } else if (qName.equalsIgnoreCase("lastName")) {
            hasLastName = true;

    public void endElement(String uri, String localName, String qName) throws SAXException {
        if (qName.equalsIgnoreCase("User")) {
            // add User object to list

    public void characters(char ch[], int start, int length) throws SAXException {

        if (hasAge) {
            // age element, set User age
            user.setAge(Integer.parseInt(new String(ch, start, length)));
            hasAge = false;
        } else if (hasFirstName) {
            user.setFirstName(new String(ch, start, length));
            hasFirstName = false;
        } else if (hasLastName) {
            user.setLastName(new String(ch, start, length));
            hasLastName = false;
        } else if (hasGender) {
            user.setGender(new String(ch, start, length));
            hasGender = false;

3. Create User class (populate XML data into User object)

So this XML is the list of users, to read this XML file we will create a bean object User and then we will parse the XML to get the list of users.
Here is the User bean object.
package net.javaguides.javaxmlparser.sax;

public class User {
    private int id;
    private String firstName;
    private String lastName;
    private int age;
    private String gender;

    public int getId() {
        return id;

    public void setId(int i) { = i;

    public String getFirstName() {
        return firstName;

    public void setFirstName(String firstName) {
        this.firstName = firstName;

    public String getLastName() {
        return lastName;

    public void setLastName(String lastName) {
        this.lastName = lastName;

    public int getAge() {
        return age;

    public void setAge(int age) {
        this.age = age;

    public String getGender() {
        return gender;

    public void setGender(String gender) {
        this.gender = gender;

    public String toString() {
        return "User [id=" + id + ", firstName=" + firstName + ", lastName=" + lastName + ", age=" + age + ", gender=" +
            gender + "]";

4. Program to Read XML File in Java using Java SAX Parser

package net.javaguides.javaxmlparser.sax;

import java.util.List;

import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.xml.sax.SAXException;

public class ReadXMLSAXParser {
    public static void main(String[] args) {
        SAXParserFactory saxParserFactory = SAXParserFactory.newInstance();
        try {
            SAXParser saxParser = saxParserFactory.newSAXParser();
            UserHandler handler = new UserHandler();
            saxParser.parse(new File("sax_users.xml"), handler);
            // Get Users list
            List < User > userList = handler.getEmpList();
            // print user information
            for (User user: userList)
        } catch (ParserConfigurationException | SAXException | IOException e) {
An output of the above program is:
User [id=1, firstName=Ramesh, lastName=Fadatare, age=28, gender=Male]
User [id=2, firstName=John, lastName=Cena, age=45, gender=Male]
User [id=3, firstName=Tom, lastName=Cruise, age=40, gender=Male]
In this tutorial, we have read an XML document with Java SAX.

Free Spring Boot Tutorial | Full In-depth Course | Learn Spring Boot in 10 Hours

Watch this course on YouTube at Spring Boot Tutorial | Fee 10 Hours Full Course