BackendBench
Coffee

Unravel › Java concepts › I/O and files

I/O and data

XML parsing: DOM, SAX, StAX

Java reads XML three ways: DOM loads the whole document into a tree you can query, SAX and StAX stream through it event by event, and JAXB or Jackson XML map elements onto classes.

Learn these first

At a glance

Mental model

DOM is photocopying the entire book so you can flip around freely.

What happens, in order
  1. 1DOM: DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(file) returns a Document; doc.getElementsByTagName("item") finds nodesEasy, but the whole file lives in memory.
  2. 2StAX: XMLStreamReader lets you pull events (START_ELEMENT, CHARACTERS) in a loop; SAX pushes the same events into your DefaultHandlerBoth use almost no memory and suit huge files.
  3. 3XPath: xpath.evaluate("/orders/order[@id='7']/total", doc) selects values with a query language; Transformer writes a DOM back to text
  4. 4Binding: JAXB (@XmlRootElement) and Jackson XmlMapper convert XML to and from objects
Remember
Watch out
Leaving external entity processing enabled on untrusted XMLForgetting namespace awarenessLoading a very large file as DOM
Example (highlighted lines explain it)
import javax.xml.XMLConstants;import javax.xml.parsers.*;import org.w3c.dom.*;import java.io.File;public class Orders {  static int count(File xml) throws Exception {    DocumentBuilderFactory f = DocumentBuilderFactory.newInstance();    f.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true);    f.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);    Document doc = f.newDocumentBuilder().parse(xml);    NodeList items = doc.getElementsByTagName("order");    return items.getLength();  }}
  1. line 7 uses DocumentBuilderFactory, the core of XML parsing: DOM, SAX, StAX
  2. line 11 uses getElementsByTagName, the core of XML parsing: DOM, SAX, StAX
Read the full explanation (about 1 min)

Java reads XML three ways: DOM loads the whole document into a tree you can query, SAX and StAX stream through it event by event, and JAXB or Jackson XML map elements onto classes.

A mental model

DOM is photocopying the entire book so you can flip around freely. SAX is a reader who calls out each chapter title as they turn the pages. Mapping libraries are a translator that hands you finished objects.

How it works

DOM: DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(file) returns a Document; doc.getElementsByTagName("item") finds nodes. Easy, but the whole file lives in memory.

StAX: XMLStreamReader lets you pull events (START_ELEMENT, CHARACTERS) in a loop; SAX pushes the same events into your DefaultHandler. Both use almost no memory and suit huge files.

XPath: xpath.evaluate("/orders/order[@id='7']/total", doc) selects values with a query language; Transformer writes a DOM back to text.

Binding: JAXB (@XmlRootElement) and Jackson XmlMapper convert XML to and from objects.

Going deeper

Security: XML parsers can fetch files and URLs through external entities (XXE) and expand "billion laughs" bombs. Disable DTDs: factory.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true) and set XMLConstants.FEATURE_SECURE_PROCESSING.

Namespaces make getElementsByTagName miss elements; use the NS variants and setNamespaceAware(true). Whitespace between elements shows up as text nodes in DOM.

For small config files DOM is fine; for gigabytes of data stream with StAX.

Under the hood

The JDK includes Xerces as the default implementation behind these factories; newInstance() looks for a provider on the class path first, so another XML library can change the parser used. DOM nodes are objects with parent and sibling links, typically 5 to 10 times the size of the text.

Common mistakes

  • Leaving external entity processing enabled on untrusted XML.
  • Forgetting namespace awareness.
  • Loading a very large file as DOM.

How Unravel recognises it

When you paste code, Unravel looks for these signs of xml parsing: dom, sax, stax. Spotting them yourself is a good habit when you read unfamiliar code:

Part of a learning path

Related concepts

Frequently asked questions

What is XML parsing: DOM, SAX, StAX?

Java reads XML three ways: DOM loads the whole document into a tree you can query, SAX and StAX stream through it event by event, and JAXB or Jackson XML map elements onto classes.

What are the most common mistakes with XML parsing: DOM, SAX, StAX?

Leaving external entity processing enabled on untrusted XML. Forgetting namespace awareness. Loading a very large file as DOM.

How can I see XML parsing: DOM, SAX, StAX in real code?

Paste your own Java into Unravel and it will point out where xml parsing: dom, sax, stax appears, explain how it works at the detail level you choose, and draw the flow of the code around it.