XML parsing using SAX parser in java

In java we have multiple ways to parse XML. We will see steps for XML parsing using SAX parser in java in this post.

What are SAX parsers?
SAX parsers are event based parsers. SAX parsers parse the XML line by line, hence do not create any document in the memory.

When to use SAX parsers?
1. When you want to process the XML line by line
2. When you have a large XML. SAX parse do not store the XML in memory, hence they can be faster than DOM parser’s for large XML’s.
3. When you only want to traverse the XML in forward manner, as SAX parsers do not allow backward traversing as supported by DOM parser.

Steps for XML parsing using SAX parser in java

SAX parser use callback function (org.xml.sax.helpers.DefaultHandler) to inform about the XML document structure that was parsed.

below are some of the important methods that need to be used while parsing

Example

1. Complete XML

2. Add a XML Handler that extends the DefaultHandler provided and use the above methods to parse the XML.

3. Create a main class that will call the XML handler and display the output.

Output

Reference

Java Doc for SAX parser

It's only fair to share...Share on FacebookShare on Google+Tweet about this on TwitterShare on LinkedIn