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.
Reading Values with the Cursor API
StAX offers two styles. The cursor API (XMLStreamReader) is low level and fast: one reader moves forward through the document. The iterator API (XMLEventReader) returns event objects you can store or pass around, which is a little heavier but more flexible.
Here is a fuller cursor example that reads attribute values and element text from a course catalogue.
<catalog>
<course id="J101"><name>Core Java</name><hours>60</hours></course>
<course id="P201"><name>Python Basics</name><hours>40</hours></course>
</catalog>
XMLInputFactory factory = XMLInputFactory.newInstance();
factory.setProperty(XMLInputFactory.SUPPORT_DTD, false);
factory.setProperty(XMLInputFactory.IS_SUPPORTING_EXTERNAL_ENTITIES, false);
try (InputStream in = new FileInputStream("catalog.xml")) {
XMLStreamReader r = factory.createXMLStreamReader(in);
String id = null;
while (r.hasNext()) {
if (r.next() == XMLStreamConstants.START_ELEMENT) {
switch (r.getLocalName()) {
case "course" -> id = r.getAttributeValue(null, "id");
case "name" -> System.out.println(id + ": " + r.getElementText());
case "hours" -> System.out.println(" hours = " + r.getElementText());
}
}
}
r.close();
}
The method getElementText() reads all text inside a simple element and moves the cursor to its end tag, which saves you from handling CHARACTERS events by hand. Note that it fails if the element contains child elements.
Writing XML with XMLStreamWriter
StAX can also produce XML as a stream, which is useful for large exports.
XMLOutputFactory out = XMLOutputFactory.newInstance();
XMLStreamWriter w = out.createXMLStreamWriter(new FileWriter("report.xml"));
w.writeStartDocument();
w.writeStartElement("report");
w.writeStartElement("item");
w.writeAttribute("code", "J101");
w.writeCharacters("Core Java & OOP"); // special characters are escaped for you
w.writeEndElement();
w.writeEndElement();
w.writeEndDocument();
w.close();
Safe Configuration and Common Mistakes
Turning off DTD and external entity support, as in the reading example, protects your application from XML External Entity (XXE) problems when files come from outside sources. Make this your default for untrusted input.
- Forgetting whitespace events. Line breaks between tags arrive as
CHARACTERSevents; checkr.isWhiteSpace()before using text. - Not closing the reader or stream, which leaks file handles in long-running services.
- Going backwards. A stream reader moves only forward. If you need random access, collect values into objects as you go or use DOM on smaller files.
- Ignoring namespaces. Use
getNamespaceURI()along with the local name when documents mix vocabularies.
Quick checklist: secure the factory, use try-with-resources, handle only the events you need, and stop reading once the required data is found.
Using the Event Iterator API
When you want to peek at the next event without consuming it, or pass events to other methods, the iterator style is more convenient. Each call returns an XMLEvent object that you can inspect and convert.
XMLEventReader events = factory.createXMLEventReader(new FileInputStream("catalog.xml"));
while (events.hasNext()) {
XMLEvent e = events.nextEvent();
if (e.isStartElement()) {
StartElement start = e.asStartElement();
Attribute id = start.getAttributeByName(new QName("id"));
if (id != null) System.out.println("Course id: " + id.getValue());
}
}
Choose the cursor API for raw speed on huge files and the iterator API when readability or filtering matters more. Both stream the document, so memory use stays low either way. A good habit is to wrap the reading logic in a small method that returns plain Java objects, so the rest of your application never needs to know StAX was used at all.