Read XML file using SAX in Java

We had a look at how to read an XML file using the DOM in Java in the previous tutorial. This tutorial introduces you to another way to read XML file faster and use less memory than the DOM, which is using SAX in Java.

That’s because the way SAX works is so different from the DOM, it does not load the contents of an XML file into memory or create any object that holds information about the XML file. Instead, it uses the callback methods of the org.xml.sax.helpers.DefaultHandler object to read the XML file from top to bottom.

For you to understand more, I have the following example:

Read XML file using SAX in Java

The contents of the XML file are as follows:

Here, I use a Student object to store the readable information of the XML file, the contents of the Student class as follows:

To read the XML file using SAX, we will first use the callback methods in the DefaultHandler object to read the XML file content. Imagine, we have an XML file and we will read its contents from top to bottom, from outside to inside following the hierarchical order.

The DefaultHandler object has the following callback methods:

  • startDocument() and endDocument(): These two methods will be called when we start reading and finishing reading the XML file.
  • startElement() and endElement(): These two methods are called when we start reading a tag in an XML file.
  • characters(): This method is called when we read the content between the two tabs of an XML file.

I will write the DefaultHandler object to read the students.xml XML file as follows:

Now that we have a handler object, we will initialize the SAXParser object to use the handler object to read the XML file.

Next, we will call the parse() method of the SAXParser object to start reading the XML file.

View list of students after reading:

Result:

Read XML file using SAX in Java

Full code for your reference:

Add Comment