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.
Main advantage of using Sax parser are given below:
Main disadvantage of using Sax parser are given below:
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.
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 BookCatalogHandler.java. Source code of my custom content handler class is given below:
In next step I created my Sax parser class BookSaxParser.java. Source of BookSaxParser.java is given below:
Here is Main class from where I am intiating sax parsing.