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:

book.xml

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

BookCatalog.java

Book.java

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 BookCatalogHandler.java. Source code of my custom content handler class is given below:

BookCatalogHandler.java

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

BookSaxParser.java

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

BookSaxParserMain.java

Result

Share & Like

About ApnaTutorials.com

ApnaTutorials.com 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.