StAX Parser
Estimated study time: 13 minutes.
StAX (Streaming API for XML) is a pull-based parsing model that combines the memory efficiency of SAX with a simpler, more intuitive programming style — your code pulls the next event when it's ready, instead of reacting to callbacks.
Push vs Pull Parsing
- SAX (push) — the parser controls the flow, calling your callback methods as it encounters events.
- StAX (pull) — your code controls the flow, requesting the next event from the parser in a loop.
Example (Java)
XMLInputFactory factory = XMLInputFactory.newInstance();
XMLStreamReader reader = factory.createXMLStreamReader(new FileReader("course.xml"));
while (reader.hasNext()) {
int event = reader.next();
if (event == XMLStreamConstants.START_ELEMENT) {
System.out.println("Start: " + reader.getLocalName());
}
}
Why Choose StAX?
- Streams the document like SAX, so it scales well to large files.
- Easier to reason about than SAX's callback-driven style — code reads top-to-bottom.
- Supports both reading and writing XML streams.
- Lets you stop parsing early once you've found what you need.
StAX vs DOM vs SAX
Think of it as a spectrum: DOM trades memory for convenience, SAX trades convenience for memory efficiency, and StAX aims for a practical middle ground — memory-efficient like SAX, but easier to write and control like DOM.
💡 Tip: StAX is a strong default choice in Java when you need to process large XML files without loading everything into memory, but still want manageable, linear code.