- Both are XML parser, that process the XML document to breaks up the text (element) into small identifiable pieces and which are finally mapped to Objects for application to process the elements.
- Document Object Model (DOM) processes the entire document and stores the object in a tree structure to manipulate.
- Simple API for XML (SAX) processes the document as it being read (like streams), generate events based on tags and events are handled by the event handler.
DOM: A tree-based processing
DOM processes the XML document and loads the data into memory in a tree-like structure. Consider the following XML code snippet:- <?xml version="1.0"?>
- <users>
- <user ID=”1”>
- <fname>John</fname>
- <lname>Doe</lname>
- <email>jdoe@force.com</email>
- </user>
- </users>
SAX: An event-based processing
SAX analyzes an XML stream as it goes by. The above example document generates the following events:- Start document
- Start element (users)
- Characters (white space)
- Start element (user) with Attribute (ID="1")
- Characters (white space)
- Start element (fname)
- Characters (John)
- End element (fname)
- Characters (white space)
- Start element (lname)
- Characters (Doe)
- End element (lname)
- Characters (white space)
- Start element (email)
- Characters (jdoe@force.com)
- End element (email)
- Characters (white space)
- End element (user)
- End element (users)
The SAX API allows a developer to capture these events and act on them.
Pros and Cons
DOM
DOM
|
SAX
|
Slow processing
|
Fast processing
|
Cost more resource
|
Cost less resource
|
Inefficient processing
|
Efficient processing
|
Non persistent
|
Persistent
|
When to choose DOM and SAX?
Depending on following factors, we can choose DOM or SAX,Application purpose
If application needs to refer back to processed data, make changes to the data and output it as XML, then DOM is a choice. Still SAX can be used, but the process is complex, as the application has to make changes to a copy of the data rather than the original data itself.
XML data size
For large files, SAX is a better choice, since it processes the XML data as streams.
Need for speed
SAX implementations are normally faster than DOM implementations.
SAX and DOM are two implementations of parsing XML data, so we can use DOM to create stream of SAX events, and SAX to create a DOM tree.
No comments:
Post a Comment