Skip to content
XML

DOM and SAX Parsing

Two models for reading XML.

By EZ4Code Team
domsaxparser

Code

<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/xsl" href="style.xsl"?>
<!-- DOM: loads the whole tree into memory; random access, editable -->
<!-- SAX: event-driven streaming; low memory, forward-only, read-only -->
<catalog parser="dom-or-sax">
  <item id="1">DOM builds a node tree you can query with XPath</item>
  <item id="2">SAX fires startElement/endElement callbacks per node</item>
  <item id="3">Use DOM for small docs, SAX for huge streams</item>
</catalog>

Explanation

DOM parsers load the entire document into a navigable tree, allowing XPath queries and mutation at the cost of memory. SAX parsers walk the document once, emitting events for elements and text, which is memory-efficient but read-only and forward-only. Choose DOM for small interactive documents and SAX for large data pipelines.

More XML Snippets