How do I build object from XML file using SAX?

This example will show you how to parse an XML file using SAX parser and build an object graph from the parsed XML. We will read the records.xml file that contains some recording information and create the Record object from it.

The DefaultHandler in this example created as an anonymous class. We override some method related to the ContentHandler interface such as the startElement, endElement and characters methods.

package org.kodejava.xml;

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

import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import java.util.ArrayList;
import java.util.List;
import java.util.Stack;


public class SAXDataDemo {
    // List of our records.
    private final List<Record> records = new ArrayList<>();

    // Stacks for storing the elements and objects.
    private final Stack<String> elements = new Stack<>();
    private final Stack<Record> objects = new Stack<>();

    public static void main(String[] args) {
        SAXDataDemo demo = new SAXDataDemo();;

    private void run() {
        try {
            SAXParserFactory factory = SAXParserFactory.newInstance();
            SAXParser parser = factory.newSAXParser();

            String filename = "/records.xml";
            InputStream is = getClass().getResourceAsStream(filename);

            parser.parse(is, new DefaultHandler() {
                public void startElement(String uri, String localName, String qName,
                                         Attributes attributes) throws SAXException {
                    if ("record".equals(qName)) {
                        Record record = new Record();

                public void endElement(String uri, String localName,
                                       String qName) throws SAXException {

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

                    String value = new String(ch, start, length);
                    if (value.length() == 0) {

                    if ("title".equals(currentElement())) {
                        Record record = objects.peek();
                    } else if ("artist".equals(currentElement())) {
                        Record record = objects.peek();
                    } else if ("genre".equals(currentElement())) {
                        Record record = objects.peek();
                    } else if ("year".equals(currentElement())) {
                        Record record = objects.peek();
        } catch (Exception e) {

        for (Record record : records) {
            System.out.println("record = " + record);

    private String currentElement() {
        return elements.peek();

The Record class.


public class Record {
    private String title;
    private String artist;
    private String genre;
    private int year;

    public Record() {

    public void setTitle(String title) {
        this.title = title;

    public void setArtist(String artist) {
        this.artist = artist;

    public void setGenre(String genre) {
        this.genre = genre;

    public void setYear(int year) {
        this.year = year;

    public String toString() {
        return "Record{" +
                "title='" + title + "'\n" +
                ", artist='" + artist + "'\n" +
                ", genre='" + genre + "'\n" +
                ", year=" + year +

The following XML is the content of our records.xml file.

<?xml version="1.0"?>
            <title>Brand New Eyes</title>
            <genre>Punk Rock</genre>
            <title>Rock Beatles</title>
            <artist>Various Artist</artist>

When we run this example will get the following output:

record = Record{title='Brand New Eyes'
, artist='Paramore'
, genre='Punk Rock'
, year=2011}
record = Record{title='Rock Beatles'
, artist='Various Artist'
, genre='Rock'
, year=2010}

Leave a Reply

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