Streaming XML Parsers in Java: SAX and StAX
Process large XML documents without building a tree: SAX callbacks with DefaultHandler, startElement, characters and endElement, StAX pull parsing with XMLStreamReader and XMLEventReader, getElementText, skipping subtrees, filters, factory properties and safe settings.
kvi5hnuCode Sprout team member10 min readOn this page
A DOM parser reads the entire document into memory before you see any of it. The tree typically takes several times the size of the file, so a few hundred megabytes of XML can exhaust the heap. And if you only want a few values, building the tree is wasted work. Streaming parsers report the document as they read it, piece by piece, and keep nothing. Memory use stays small and constant no matter how large the input is.
The JDK has two streaming APIs:
- SAX (Simple API for XML), from 1998, is a push parser. You hand it a handler object, and it calls your methods for each start tag, piece of text and end tag.
- StAX (Streaming API for XML, Java 6) is a pull parser. Your code asks for the next event in a loop, like an iterator.
Both are part of the java.xml module. In fact, the JDK's DOM builder runs on the same streaming engine (the internal Xerces pipeline that also drives SAX): it creates nodes as the parsing events arrive.
SAX
Get a parser from a factory, then pass the source and a handler to parse:
SAXParserFactory factory = SAXParserFactory.newNSInstance(); // namespace-aware (Java 13)
SAXParser parser = factory.newSAXParser();
parser.parse(source, handler); // File, URI string, InputStream or InputSource
The handler is usually a subclass of DefaultHandler, which implements the four SAX callback interfaces (ContentHandler, ErrorHandler, DTDHandler, EntityResolver) with empty methods. You override only what you need. The most important callbacks:
| Method | Called for |
|---|---|
startDocument(), endDocument() | the start and end of the input |
startElement(uri, localName, qName, attributes) | each start tag |
endElement(uri, localName, qName) | each end tag |
characters(ch, start, length) | character data |
ignorableWhitespace(ch, start, length) | whitespace in element-only content, when a DTD says so |
processingInstruction(target, data) | processing instructions |
error(e), fatalError(e), warning(e) | problems |
With a namespace-aware parser, uri and localName describe the element, and qName is the name as written. Without namespace awareness, which is the default for SAXParserFactory.newInstance(), only qName is filled in, and localName is empty. Attributes gives access by index (getLength, getLocalName(i), getURI(i), getQName(i), getValue(i)), by qualified name (getValue("href")), or by namespace and local name. A missing attribute yields null.
Here is a handler that prints every link in an XHTML page:
parser.parse(in, new DefaultHandler() {
@Override
public void startElement(String uri, String localName, String qName, Attributes attrs) {
if (localName.equals("a")) {
String href = attrs.getValue("href");
if (href != null) System.out.println(href);
}
}
});
That's SAX at its best. The context in which the a elements occur doesn't matter, and nothing needs to be stored.
Once the processing depends on context ("the total inside an order from region X"), a SAX handler turns into a state machine. You track in fields where you are, collect text, and act on end tags. That works, but it's easy to get wrong. That's where StAX is more pleasant.
To keep an XHTML parser from downloading the XHTML DTD (see article 41), turn off external DTD loading for non-validating parsers:
factory.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);
StAX: pulling events
With StAX, the loop belongs to you:
XMLInputFactory factory = XMLInputFactory.newInstance();
XMLStreamReader reader = factory.createXMLStreamReader(in); // InputStream, Reader or Source
while (reader.hasNext()) {
int event = reader.next();
if (event == XMLStreamConstants.START_ELEMENT && reader.getLocalName().equals("a")) {
String href = reader.getAttributeValue(null, "href");
...
}
}
reader.close();
next() advances to the next event and returns its type as an int constant from XMLStreamConstants: START_ELEMENT, END_ELEMENT, CHARACTERS, CDATA, SPACE, COMMENT, PROCESSING_INSTRUCTION, START_DOCUMENT, END_DOCUMENT and a few more. Which accessor methods are allowed depends on the current event:
| Event | Useful methods |
|---|---|
START_ELEMENT | getLocalName(), getNamespaceURI(), getPrefix(), getName(), getAttributeCount(), getAttributeValue(ns, local), getElementText() |
END_ELEMENT | getLocalName(), getName() |
CHARACTERS, CDATA, SPACE, COMMENT | getText(), getTextCharacters(), isWhiteSpace() |
| any | getEventType(), getLocation() (line and column) |
For the fragment
<font>
<name>Helvetica</name>
<size unit="pt">36</size>
</font>
you get START_ELEMENT font, whitespace CHARACTERS, START_ELEMENT name, CHARACTERS "Helvetica", END_ELEMENT name, and so on.
Two methods make pull parsing particularly convenient:
getElementText(), called on aSTART_ELEMENTof a text-only element, reads all its text (however it's split) and leaves the reader on the matchingEND_ELEMENT.nextTag()skips whitespace, comments and processing instructions up to the next start or end tag. It throws if it finds other text.
Because your code drives the parser, you can also skip whole subtrees you don't care about (the demo does this with a depth counter), stop as soon as you have what you need, or pass the reader to helper methods that each parse one kind of element. State lives in local variables instead of handler fields.
Unlike SAX and DOM, StAX is namespace-aware by default. Pass null as the namespace argument of getAttributeValue to match an attribute by local name only.
The event iterator API
StAX has a second, object-based style. An XMLEventReader is an Iterator of XMLEvent objects (StartElement, Characters, EndElement and so on):
XMLEventReader events = factory.createXMLEventReader(in);
while (events.hasNext()) {
XMLEvent e = events.nextEvent();
if (e.isStartElement()) {
StartElement start = e.asStartElement();
Attribute id = start.getAttributeByName(new QName("id"));
...
}
}
Events are immutable objects, so you can store them, pass them around, look ahead with peek(), and write them back out with an XMLEventWriter (article 46). The cursor API is faster and creates less garbage. The event API is more flexible. createFilteredReader wraps either kind with a filter that hides the events you don't want.
Factory properties
| Property | Default | Meaning |
|---|---|---|
XMLInputFactory.IS_NAMESPACE_AWARE | true | process namespaces |
XMLInputFactory.IS_COALESCING | false | merge adjacent text and CDATA into one event |
XMLInputFactory.IS_REPLACING_ENTITY_REFERENCES | true | report entity replacement text as characters |
XMLInputFactory.IS_SUPPORTING_EXTERNAL_ENTITIES | true | resolve external entities |
XMLInputFactory.SUPPORT_DTD | true | process DTDs |
XMLInputFactory.IS_VALIDATING | false | validate (not supported by the JDK implementation) |
For untrusted input, set SUPPORT_DTD and IS_SUPPORTING_EXTERNAL_ENTITIES to false. The considerations from article 40 apply here as well.
Choosing a parser
| DOM | SAX | StAX | |
|---|---|---|---|
| Style | whole tree in memory | callbacks pushed to you | events pulled by you |
| Memory | proportional to the document | constant | constant |
| Random access, modification | yes | no | no |
| Code for context-dependent data | simple | a state machine | a natural loop or recursive descent |
| Namespace-aware by default | no | no | yes |
| Can stop early | no | only by throwing an exception | yes |
Use DOM (often with XPath) for documents that fit comfortably in memory and for anything that needs navigation or modification. Use StAX for large inputs or when you want to stop early. SAX is still widely used by existing code and libraries, and its event model is also handy for producing XML from other data (article 47).
The program
The demo first runs a SAX handler over a small XHTML snippet. Note how characters delivers Fish , &, chips and the CDATA content in separate calls. It then prints the StAX events for the font fragment. Next it generates an order file of about three megabytes and computes totals per region three ways: with a SAX state machine, with a StAX cursor loop that skips the notes subtree and uses getElementText, and with a filtered event reader. The results agree. Finally, it shows StAX error reporting and the effect of disabling DTDs.
import java.io.*;
import java.math.BigDecimal;
import java.nio.charset.StandardCharsets;
import java.nio.file.*;
import java.util.*;
import javax.xml.parsers.*;
import javax.xml.stream.*;
import javax.xml.stream.events.*;
import org.xml.sax.*;
import org.xml.sax.helpers.DefaultHandler;
public class Solution {
static final String PAGE = """
<html xmlns="http://www.w3.org/1999/xhtml">
<body>
<p>See <a href="https://openjdk.org">OpenJDK</a> and
<a href="/docs/api/" title="API">the API</a>.</p>
<a name="anchor-only">no link</a>
<p>Fish & chips <![CDATA[<raw>]]> done</p>
</body>
</html>""";
/** Writes a big order file without building it in memory. */
static void generate(Path file, int orders) throws IOException {
try (var out = Files.newBufferedWriter(file, StandardCharsets.UTF_8)) {
out.write("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<orders>\n");
for (int i = 1; i <= orders; i++) {
String region = switch (i % 3) { case 0 -> "north"; case 1 -> "south"; default -> "west"; };
out.write(" <order id=\"" + i + "\" region=\"" + region + "\">\n");
out.write(" <customer>Customer " + (i % 50) + "</customer>\n");
out.write(" <notes><note>gift</note><note>fragile</note></notes>\n");
out.write(" <total>" + (i % 100) + "." + String.format("%02d", i % 97) + "</total>\n");
out.write(" </order>\n");
}
out.write("</orders>\n");
}
}
public static void main(String[] args) throws Exception {
System.out.println("--- SAX: callbacks ---");
SAXParserFactory saxFactory = SAXParserFactory.newNSInstance();
SAXParser sax = saxFactory.newSAXParser();
var events = new ArrayList<String>();
sax.parse(new InputSource(new StringReader(PAGE)), new DefaultHandler() {
@Override
public void startElement(String uri, String localName, String qName, Attributes attrs) {
if (localName.equals("a")) {
String href = attrs.getValue("href");
events.add("link " + (href == null ? "(none)" : href) + " with " + attrs.getLength() + " attribute(s)");
}
}
@Override
public void characters(char[] ch, int start, int length) {
String s = new String(ch, start, length);
if (s.contains("chips") || s.contains("raw") || s.contains("&")) events.add("characters \"" + s + "\"");
}
});
events.forEach(System.out::println);
System.out.println("--- StAX: the cursor API ---");
XMLInputFactory inFactory = XMLInputFactory.newInstance();
inFactory.setProperty(XMLInputFactory.SUPPORT_DTD, false); // safe defaults
inFactory.setProperty(XMLInputFactory.IS_SUPPORTING_EXTERNAL_ENTITIES, false);
XMLStreamReader reader = inFactory.createXMLStreamReader(new StringReader(
"<font>\n <name>Helvetica</name>\n <size unit=\"pt\">36</size>\n</font>"));
while (reader.hasNext()) {
int event = reader.next();
switch (event) {
case XMLStreamConstants.START_ELEMENT -> System.out.println("START_ELEMENT " + reader.getLocalName()
+ (reader.getAttributeCount() > 0 ? " unit=" + reader.getAttributeValue(null, "unit") : ""));
case XMLStreamConstants.CHARACTERS -> System.out.println("CHARACTERS " + (reader.isWhiteSpace()
? "(whitespace)" : "\"" + reader.getText() + "\""));
case XMLStreamConstants.END_ELEMENT -> System.out.println("END_ELEMENT " + reader.getLocalName());
case XMLStreamConstants.END_DOCUMENT -> System.out.println("END_DOCUMENT");
default -> System.out.println("event " + event);
}
}
reader.close();
Path file = Files.createTempFile("orders", ".xml");
try {
generate(file, 20_000);
System.out.println("--- a large file: " + Files.size(file) / 1024 + " KiB ---");
// SAX: a state machine that collects text between start and end tags
var saxTotals = new TreeMap<String, BigDecimal>();
sax.parse(file.toFile(), new DefaultHandler() {
private String region;
private final StringBuilder text = new StringBuilder();
private boolean inTotal;
@Override
public void startElement(String uri, String local, String q, Attributes attrs) {
if (local.equals("order")) region = attrs.getValue("region");
else if (local.equals("total")) { inTotal = true; text.setLength(0); }
}
@Override
public void characters(char[] ch, int start, int length) {
if (inTotal) text.append(ch, start, length); // may be called several times
}
@Override
public void endElement(String uri, String local, String q) {
if (local.equals("total")) {
inTotal = false;
saxTotals.merge(region, new BigDecimal(text.toString().strip()), BigDecimal::add);
}
}
});
System.out.println("SAX totals per region: " + saxTotals);
// StAX cursor: the program drives the loop, so the state lives in local variables
var staxTotals = new TreeMap<String, BigDecimal>();
var customers = new HashSet<String>();
try (var in = Files.newInputStream(file)) {
XMLStreamReader r = inFactory.createXMLStreamReader(in, "UTF-8");
String region = null;
while (r.hasNext()) {
if (r.next() != XMLStreamConstants.START_ELEMENT) continue;
switch (r.getLocalName()) {
case "order" -> region = r.getAttributeValue(null, "region");
case "customer" -> customers.add(r.getElementText());
case "notes" -> skipElement(r); // not interested
case "total" -> staxTotals.merge(region, new BigDecimal(r.getElementText()), BigDecimal::add);
default -> { }
}
}
r.close();
}
System.out.println("StAX cursor totals: " + staxTotals + ", " + customers.size() + " customers");
// StAX event iterator: events are objects that can be kept, peeked at, or filtered
int big = 0;
try (var in = Files.newInputStream(file)) {
XMLEventReader events2 = inFactory.createFilteredReader(inFactory.createXMLEventReader(in),
e -> e.isStartElement() && e.asStartElement().getName().getLocalPart().equals("order"));
while (events2.hasNext()) {
StartElement order = events2.nextEvent().asStartElement();
Attribute id = order.getAttributeByName(new javax.xml.namespace.QName("id"));
if (Integer.parseInt(id.getValue()) % 1000 == 0) big++;
}
events2.close();
}
System.out.println("event iterator: orders with id divisible by 1000: " + big);
} finally {
Files.delete(file);
}
System.out.println("--- errors ---");
try {
XMLStreamReader bad = inFactory.createXMLStreamReader(new StringReader("<a><b></a>"));
while (bad.hasNext()) bad.next();
} catch (XMLStreamException e) {
System.out.println("StAX: line " + e.getLocation().getLineNumber() + ": "
+ e.getMessage().substring(e.getMessage().indexOf("Message: ") + 9));
}
try {
XMLStreamReader dtd = inFactory.createXMLStreamReader(new StringReader(
"<!DOCTYPE r [<!ENTITY e \"x\">]><r>&e;</r>"));
while (dtd.hasNext()) dtd.next();
} catch (XMLStreamException e) {
System.out.println("StAX with SUPPORT_DTD=false: " + e.getMessage().substring(e.getMessage().indexOf("Message: ") + 9));
}
}
/** Skips the current element and everything inside it; the reader must be on its START_ELEMENT. */
static void skipElement(XMLStreamReader r) throws XMLStreamException {
int depth = 1;
while (depth > 0) {
int e = r.next();
if (e == XMLStreamConstants.START_ELEMENT) depth++;
else if (e == XMLStreamConstants.END_ELEMENT) depth--;
}
}
}
--- SAX: callbacks ---
link https://openjdk.org with 1 attribute(s)
link /docs/api/ with 2 attribute(s)
link (none) with 1 attribute(s)
characters "&"
characters " chips "
characters "<raw>"
--- StAX: the cursor API ---
START_ELEMENT font
CHARACTERS (whitespace)
START_ELEMENT name
CHARACTERS "Helvetica"
END_ELEMENT name
CHARACTERS (whitespace)
START_ELEMENT size unit=pt
CHARACTERS "36"
END_ELEMENT size
CHARACTERS (whitespace)
END_ELEMENT font
END_DOCUMENT
--- a large file: 3219 KiB ---
SAX totals per region: {north=333230.95, south=333197.69, west=333164.43}
StAX cursor totals: {north=333230.95, south=333197.69, west=333164.43}, 50 customers
event iterator: orders with id divisible by 1000: 20
--- errors ---
StAX: line 1: The element type "b" must be terminated by the matching end-tag "</b>".
StAX with SUPPORT_DTD=false: The entity "e" was referenced, but not declared.
Common questions
How do I get the line number of an error or of the current element?
In SAX, override setDocumentLocator(Locator) and keep the locator; getLineNumber() and getColumnNumber() are valid in any callback. Exceptions are SAXParseExceptions with the same methods. In StAX, call reader.getLocation().
Can I stop a SAX parse early once I have what I need?
Throw an exception from the handler, for example a private subclass of SAXException, and catch it around parse. There is no other way, because the parser owns the loop. With StAX you simply stop calling next() and close the reader.
Does XMLStreamReader.close() close the underlying stream?
No. It frees the parser's resources only. Close the InputStream or Reader yourself, ideally with try-with-resources on the stream and a finally for the reader (it isn't AutoCloseable).
Can I process a huge file with StAX but still use DOM for each record?
Yes, a common hybrid. Move the StAX reader to each record's start tag, then pass new StAXSource(reader) to an identity Transformer with a DOMResult (article 46). That builds a small tree for one record, which you can query with XPath, then you continue streaming.
Why is localName empty in my SAX handler?
The factory isn't namespace-aware. Use SAXParserFactory.newNSInstance(), or read qName instead.
SAX or StAX for new code?
StAX in most cases: your code controls the loop, state lives in local variables, and it can also write XML. SAX remains useful when an API hands you a ContentHandler slot, as in SAXResult or XMLFilter pipelines.
API reference
| API | Purpose |
|---|---|
SAXParserFactory.newInstance(), newNSInstance() | SAX factories (non-aware / namespace-aware) |
SAXParser.parse(source, handler) | parse, reporting events to a DefaultHandler |
DefaultHandler.startElement, endElement, characters | the main SAX callbacks |
Attributes.getValue(qName), getValue(uri, local), getLength() | attribute access in SAX |
XMLInputFactory.newInstance(), setProperty(name, value) | StAX factory and its settings |
createXMLStreamReader(InputStream / Reader / Source) | cursor-style reader |
XMLStreamReader.hasNext(), next(), nextTag() | advance through events |
XMLStreamReader.getLocalName(), getAttributeValue(ns, name), getText(), getElementText() | event details |
createXMLEventReader(...), XMLEventReader.nextEvent(), peek() | event-object style |
createFilteredReader(reader, filter) | hide unwanted events |
XMLStreamException.getLocation() | position of an error |
Summary
- Streaming parsers use constant memory and suit large documents and single-pass extraction. DOM builds the whole tree.
- SAX pushes events into a
DefaultHandler. OverridestartElement,endElementandcharacters, and keep context in fields. - Text may arrive in several
characterscalls. Accumulate it before using it. - StAX lets your code pull events with
XMLStreamReader.next().getElementText,nextTagand early exits make the code straightforward. XMLEventReaderoffers immutable event objects, peeking and filtering.- SAX and DOM need namespace awareness turned on. StAX has it on by default. Disable DTDs and external entities for untrusted input.
Practice Questions
A SAX handler stores the text from characters directly into a field and sometimes ends up with only part of a value. Why, and how do you fix it?
The parser can split one text run into several characters calls, for example at buffer boundaries or around entity references. Clear a StringBuilder in startElement, append in every characters call, and use the accumulated text in endElement.
What does getElementText() do, and on which event may you call it?
It must be called when the reader is on a START_ELEMENT of an element with text-only content. It concatenates all the text (including CDATA and entity replacements) up to the matching end tag, leaves the reader on that END_ELEMENT, and throws an exception if it encounters a child element.
You need just the \<title\> from a 2 GB XML file in which it appears near the start. Which parser and why?
StAX. You read events until the title start element, call getElementText(), and stop, without reading the rest of the file. DOM would load all 2 GB into memory, and SAX would keep reading to the end unless you abort it by throwing an exception from the handler.
Why does attrs.getValue("href") work but localName.equals("a") fail in a SAX handler created by SAXParserFactory.newInstance()?
That factory produces non-namespace-aware parsers, which report an empty localName and put the name only into qName. Either compare qName, or create the factory with SAXParserFactory.newNSInstance() (or call setNamespaceAware(true)). Attribute lookup by qualified name works in both modes.
What's the difference between the StAX cursor API and the event iterator API?
The cursor API (XMLStreamReader) keeps a single mutable reader positioned on the current event, which you query with methods such as getLocalName(). It's the fastest option. The iterator API (XMLEventReader) returns a new immutable XMLEvent object for each event, which you can store, peek at, filter or pass to an XMLEventWriter, at the cost of extra allocations.
Previous: XML Namespaces: Prefixes, Default Namespaces and Namespace-Aware Parsing
Next: Generating XML in Java: Building DOM Trees and Writing with Transformer, LSSerializer and StAX
Related reading
- Java Directory Traversal: Files.list, walk, find, Glob Patterns and FileVisitor
- Java ZIP Archives: ZipInputStream, ZipOutputStream and ZIP File Systems
- Java I/O Filters: Buffered, Data and Pushback Streams
- Java I/O Streams: Reading and Writing Bytes
- Java Parallel Streams: When They Help, Ordering and Thread Safety

More in Core Java II
FFM Upcalls, Variadic Functions and errno
Advanced FFM calls: passing Java code to C as function pointers with upcall stubs, binding objects and lambdas, calling variadic functions such as printf, capturing errno and GetLastError, and a C library that calls back into Java. The final article of the course.
Calling Foreign Functions: Linker, Symbol Lookup, Downcalls and jextract
Calling C functions from pure Java with the FFM API: the native linker, default, library and loader symbol lookups, function descriptors, downcall handles, invokeExact, pointers and NULL, struct results, critical calls, enabling native access, and generating bindings with jextract.
FFM Memory Layouts: Structs, Unions, Sequences and Var Handles
Describing C data with FFM memory layouts: value layouts and C types, struct and union layouts, alignment and padding, sequences, layout paths, var handles with base offsets, offset and slice handles, pointers with target layouts, and atomic access modes.
Foreign Function and Memory API: Arenas and Memory Segments
Getting started with the FFM API (final since Java 22): a first foreign call, confined, shared, automatic and global arenas, native and heap memory segments, reading and writing values, C strings and arrays, alignment and byte order, slices, copies, allocators, and memory-mapped files.
Discussion
Sign in to ask a question or share what you learned.