DOM and SAX Parser

Both DOM and SAX parserare extensively used to read and parse xml file in java and have there own set of advantage and disadvantage which we will cover in this article.

DOM Parser:

DOM Stands forDocument Object Model and it represent anXML Documentinto tree format which each element representing tree branches.DOM Parser creates an In Memory tree representation of XML file and then parses it, so it requires more memory and its advisable to have increased heap size for DOM parser in order to avoid Java.lang.OutOfMemoryError:java heap space.Parsing XML file using DOM parser is quite fast if XML file is small but if you try to read a large XML file using DOMparserthere is more chances that it will take a long time or even may not be able to load it completely simply because it requires lot of memory to create XML Dom Tree. Java provides support DOM Parsing and you can parse XML files in Java using DOMparser. DOM classes are in w3c.dom package while DOM Parser for Java is in JAXP (Java API forXML Parsing) package.

SAX Parser:

SAX Stands for Simple API for XML Parsing. This is an event based XML Parsing and it parse XML file step by step so much suitable for large XML Files. SAX XML Parser fires event when it encountered opening tag, element or attribute and the parsing works accordingly. It’s recommended to use SAX XML parser for parsing large xml files in Java because it doesn’t require to load whole XML file in Java and it can read a big XML file insmall parts. Java provides support for SAX parser and you can parse any xml file in Java using SAX Parser. One disadvantage of using SAX Parser in java is that reading XML file in Java using SAX Parser requires more code in comparison of DOM Parser.

Difference between DOM and SAX XML Parser

Here are few high level differences between DOM parser and SAX Parser in Java:

1)DOM parser loads wholexml documentin memory while SAX only loads small part of XML file in memory.
2) DOM parser is faster than SAX because it access wholeXML documentin memory.
3) SAX parser in Java is better suitable for large XML file than DOM Parser because it doesn’t require much memory.
4) DOM parser works on Document Object Model while SAX is an event based xml parser.

5)Where as, we can navigate the DOM tree in any direction, any no. of times where as in SAX parser no navigation possible (top to bottom only once).


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s