Scrivio Interview library
ConceptFoundations6 min read · updated 12 November 2026

Compare DOM, SAX and StAX on memory use, programming model, ability to modify the document and random access. Which would you pick for a 2 KB config file and for a 5 GB data export?

DOM loads the whole document into a tree in memory, which gives random access and easy modification but costs several times the file size. SAX and StAX both stream with a small, constant memory footprint and give only forward, read-only access while parsing; SAX pushes callbacks at a handler that must keep its own state, while StAX lets our code pull events and also offers a writer API. For a 2 KB config file I would use DOM with XPath, or a binding library such as Jakarta XML Binding or Jackson XML; for a 5 GB export I would use StAX, or SAX, and process one record at a time.

Why this question is asked

Java has three standard ways to parse XML, and choosing the wrong one shows up either as an OutOfMemoryError on big files or as needlessly complicated code on small ones. This is a classic interview question because the answer tells the interviewer whether we understand the shape of each API, not just its name. In this answer, we will recap each of the three models with a short example, compare them on memory, programming model, modification and random access, and then reason through the two cases in the question, including when a binding library beats all three.

1DOM: The Whole Tree in Memory

DOM, the Document Object Model, parses the entire file and gives us a Document, a tree of Node objects for elements, attributes and text. Because the whole tree exists, we can jump anywhere, go back to the parent, read the last element before the first, query with XPath, and change the tree: add elements, edit text, remove nodes, and write the result back out.

Java
Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(file);
Element root = doc.getDocumentElement();
String timeout = root.getElementsByTagName("timeout").item(0).getTextContent(); // "30"
root.getElementsByTagName("timeout").item(0).setTextContent("45"); // modify in place

The cost is memory. Every node is an object with references to its parent, children and siblings, plus strings, so the tree usually takes 5 to 10 times the size of the file, and nothing can start until the whole file has been parsed. For small documents that cost is irrelevant and DOM is the most convenient API.

2SAX: Callbacks Pushed at a Handler

SAX, the Simple API for XML, reads the file once from start to end and calls methods on a handler we provide: startElement(), characters(), endElement(). It never builds a tree, so memory stays small and constant whatever the file size. It is read-only and forward-only: once a callback has returned, that part of the document is gone.

Because the parser is in control, the handler must remember any context it needs in fields, such as which element it is inside or a buffer for text, which also has to cope with characters() being called several times for one piece of text. For simple extraction this is fine; for complex nested formats the handler can become a hard-to-read state machine.

3StAX: Our Loop Pulls Events

StAX, the Streaming API for XML, also streams with constant memory, but reverses control. We create an XMLStreamReader and call next() in our own loop. That means context can live in local variables, we can write helper methods that read one sub-element, and we can stop whenever we want. StAX also includes XMLStreamWriter for producing XML in a streaming way, which SAX lacks.

Java
XMLStreamReader r = factory.createXMLStreamReader(in);
while (r.hasNext()) {
if (r.next() == XMLStreamConstants.START_ELEMENT && r.getLocalName().equals("row")) {
process(r.getAttributeValue(null, "id")); // one row at a time, then forgotten
}
}

StAX offers a cursor style, XMLStreamReader, and an event-object style, XMLEventReader, which allows peeking ahead at the cost of allocating an object per event.

4Comparing the Three

Putting the three side by side makes the choice much easier to reason about.

DOM, SAX and StAX compared
AspectDOMSAXStAX
Memorywhole tree, 5 to 10x the filesmall and constantsmall and constant
Programming modelnavigate a treeparser pushes callbacksour code pulls events
Where state livesin the treehandler fieldslocal variables
Modify the documentyes, then serialisenono, but can write a new one
Random accessyes, and XPathno, forward onlyno, forward only
Write XMLvia TransformernoXMLStreamWriter
Best forsmall documentspipelines of handlerslarge files, new streaming code

The pattern is that DOM trades memory for convenience, while SAX and StAX trade convenience for constant memory. Between the two streaming APIs, StAX is usually easier to write and read for new code; SAX remains useful where a chain of SAX handlers or filters already exists.

5Choosing for a 2 KB Config File

A 2 KB file becomes perhaps 20 KB of DOM, which is nothing. What we want here is convenience and clarity, so DOM is the right base. With XPath we can write lookups such as /config/database/timeout in one line rather than walking nodes by hand.

Even better for configuration is often a binding library, which maps the XML to Java objects so the rest of the code works with typed fields. Jakarta XML Binding (the successor of JAXB, in the jakarta.xml.bind package) uses annotations on classes or classes generated from an XSD; Jackson's XML module maps XML to plain Java objects the same way Jackson maps JSON. Then the config becomes a Config object with an int timeout, and validation and defaults live in one place. Whichever we choose, we parse with DTDs disabled.

6Choosing for a 5 GB Data Export

A 5 GB file as DOM would need something like 25 to 50 GB of heap, so DOM is out of the question. We need streaming, and for new code I would choose StAX: loop over events, collect the fields of one record, process or write it, and let it become garbage. Memory stays at a few megabytes for the parser buffer and the current record.

If records are complex, a hybrid works well: stream with StAX to each record's start tag and let Jakarta XML Binding unmarshal just that element into an object. SAX would also work with the same memory profile, especially if the team already has SAX handlers for this format.

7Follow-up questions

Is there a size where DOM stops being reasonable?

There is no fixed number, but a useful rule is to compare 5 to 10 times the largest expected file with the memory we can spare for one request or one job, considering how many run at once. A 5 MB file is fine for a batch job but 50 concurrent 5 MB uploads in a web service already mean gigabytes. If files can grow without a limit, stream.

Where does XPath fit in?

The JDK's javax.xml.xpath evaluates expressions over a DOM tree, so it needs the whole document in memory. It is ideal for small documents. For streaming, we either extract fields by hand with StAX or use a streaming-capable processor such as Saxon's XSLT 3.0 streaming, which only supports a restricted subset of expressions.

Which API is fastest?

For reading large files, SAX and the StAX cursor are both fast and close to each other; implementation matters more than the API, and Woodstox or Aalto are often faster than the JDK default. DOM is slower overall because it allocates the whole tree, but for small files the difference is microseconds.

8Conclusion

In this answer, we compared the three standard XML APIs. DOM keeps the whole tree in memory, gives random access, XPath and modification, and suits small documents. SAX streams with constant memory by pushing callbacks at a handler that holds the state, and is read-only and forward-only. StAX also streams but lets our code pull events, keeps state in local variables and adds a streaming writer. For a 2 KB config file, DOM with XPath or a binding library like Jakarta XML Binding or Jackson XML is the clearest choice; for a 5 GB export, StAX, or SAX, processing one record at a time is the only sensible one.

What to say in the interviewAbout 90 seconds aloud

Open with

The three differ mainly in memory and who controls the flow. DOM parses the whole document into a tree of nodes. That costs roughly five to ten times the file size, but I get random access, I can go up and down the tree, use XPath, and modify the document and serialise it again.

Then, if they want more

SAX and StAX are streaming parsers with small constant memory, and both are read-only and forward-only while parsing. With SAX the parser pushes callbacks like startElement and characters into my handler, so all context lives in handler fields, and I have to buffer text because characters can be split.

With StAX I pull events in my own loop, so state is in local variables, I can stop whenever I like, and StAX also has XMLStreamWriter for writing. For a 2 KB config file I would go for convenience: DOM with XPath, or better a binding library, Jakarta XML Binding or Jackson XML, so the config becomes a typed object.

Memory is irrelevant at that size. For a 5 GB export, DOM would need tens of gigabytes, so I would stream it with StAX, process one record at a time and let it be garbage-collected, possibly unmarshalling each record with Jakarta XML Binding. SAX would also be fine if the team already uses it. In both cases I disable DTDs.

About this answer

Last updated
12 November 2026
Checked
Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the official documentation for the version you use. What the checks cover
Where the question comes from
Written by Scrivio for practice. It is not taken from an interview.
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "Compare DOM, SAX and StAX on memory use, programming model, ability to modify the...": https://scrivio-interview-library.netlify.app/java/xml-processing/e9fd702200/