Sax parser

Sax stands for Simple API for XML, is an event driven, serial access mechanism for accessing XML documents. This protocol is frequently used by servlets and network oriented programs that need to transmit and receive XML documents, because it is the fastest and least memory-intensive mechanism that is currently available for dealing with XML documents, other than the Streaming API for XML (StAX).

We will cover Streaming API for XML (StAX) in our next tutorial.

Advantage of Sax parser

Main advantage of using Sax parser are given below:

  • Sax parser are fast and can be used to parse huge xml documents.
  • Event based parsing
  • Traverse in single direction from top to bottom

Disadvantage of Sax parser

Main disadvantage of using Sax parser are given below:

  • We can't insert or delete a node
  • API is less intuitive as it is event based

When use sax parser

If xml document is huge, if we need to find a node and doesnt need to insert or delete node, if performance matters then we can go with SAX.

Sax parser example

In this example we will parse book.xml using SAX parser and populate object of corresponding class with parsed data. The xml which we are going to parse is given below:


I made 2 class to hold parsed data of book.xml are given below:

org.xml.sax.helpers.DefaultHandler provides default implementation of ContentHandler interface and we can extend this class to create our own handler.

I created my own content handler class Source code of my custom content handler class is given below:

In next step I created my Sax parser class Source of is given below:

Here is Main class from where I am intiating sax parsing.


Share & Like

About is for Java, J2ee, Html5 and android developers. All tutorials are well explained and are easy to understand. We have tested every tutorials on our developement environment before posting it in public domain.