Lesson 10 — Working with XML

Parsing XML: DOM and SAX

Programs read XML using one of two general strategies: loading the entire document into memory as a navigable tree (DOM), or streaming through it sequentially (SAX).

DOM Parsing

The DOM (Document Object Model) approach loads the entire XML document into memory as a tree, which your code can then navigate freely in any direction — searching, modifying, and re-serialising it. This is convenient, but uses more memory, which matters for very large documents.

SAX Parsing

SAX (Simple API for XML) reads a document sequentially from start to finish, firing events (like 'element started', 'text found', 'element ended') as it goes, without holding the whole tree in memory. It's efficient for very large files, but harder to work with since you can't jump around the document freely.

Choosing an Approach

For most everyday documents, DOM's convenience outweighs its memory cost. SAX (or similar streaming parsers) become valuable specifically when working with XML files too large to comfortably load entirely into memory.

Common Mistakes

  • Using DOM parsing on extremely large XML files, causing excessive memory usage or slow performance.
  • Choosing SAX for a task that requires random access or repeated traversal of the document, fighting against its sequential, one-pass nature.
  • Assuming every programming language's XML library defaults to the same parsing strategy — check documentation for the specific library you're using.
  • Forgetting to close or release resources properly when streaming very large XML files.

Professional Tip

Start with DOM parsing by default — it's simpler to reason about — and only reach for SAX or another streaming approach once you have a concrete, measured reason, like handling files too large to fit comfortably in memory.

Your Turn

Research your preferred programming language's standard library for XML parsing, and note whether it offers a DOM-style API, a SAX-style API, or both.

Mini Quiz

What is the main trade-off of DOM parsing compared to SAX parsing?