Java SAX Parser: Event-Based XML Parsing with DefaultHandler
SAX reads XML as a stream of events: a callback for each start tag, each piece of text and each end tag. Nothing is kept unless your code keeps it, so SAX can process files far larger than memory. The price is that you track the context yourself. This page explains the event model, then runs namespaces, object building, early stopping, error handling and a file larger than the heap.
Contents
How SAX works
SAX (Simple API for XML) is a push parser: you hand the parser an object with callback methods, and the parser reads the input from start to end, calling a method for each thing it finds. When startElement
SAX 2.0 dates from 2000 and has been in the JDK since Java 1.4, through JAXP's SAXParserFactoryjava.xmlDefaultHandler
| Callback | Interface | Called for |
|---|---|---|
startDocumentendDocument | ContentHandler | The start and end of the input |
startElementendElement | ContentHandler | Each start and end tag, with attributes on the start |
characters | ContentHandler | Text, in one or more chunks |
startPrefixMapping | ContentHandler | Namespace declarations |
setDocumentLocator | ContentHandler | Once, giving an object that reports the current line and column |
warningerrorfatalError | ErrorHandler | Problems; only fatalError |
resolveEntity | EntityResolver | External entities and DTDs, where XXE attacks start |
SAXParserXMLReadergetXMLReader()XMLFilter
All programs use only the JDK and were run on JDK 21.
The event sequence
To show exactly what the parser reports, the first program logs every callback with indentation for nesting. The input contains an escaped &
import java.io.StringReader;
import javax.xml.parsers.SAXParserFactory;
import org.xml.sax.Attributes;
import org.xml.sax.InputSource;
import org.xml.sax.helpers.DefaultHandler;
public class SaxEvents {
public static void main(String[] args) throws Exception {
String xml = "<order id=\"7\"><item sku=\"A1\" qty=\"2\">Pen</item>"
+ "<item sku=\"B2\" qty=\"1\">Notebook & cover</item></order>";
// The parser calls these methods as it reads; it never builds a tree
DefaultHandler logger = new DefaultHandler() {
int depth = 0;
@Override
public void startElement(String uri, String local, String qName, Attributes a) {
StringBuilder attrs = new StringBuilder();
for (int i = 0; i < a.getLength(); i++) {
attrs.append(' ').append(a.getQName(i)).append('=').append(a.getValue(i));
}
System.out.println(" ".repeat(depth++) + "start " + qName + attrs);
}
@Override
public void characters(char[] ch, int start, int length) {
System.out.println(" ".repeat(depth) + "text \"" + new String(ch, start, length)
+ "\"");
}
@Override
public void endElement(String uri, String local, String qName) {
System.out.println(" ".repeat(--depth) + "end " + qName);
}
};
SAXParserFactory.newInstance().newSAXParser()
.parse(new InputSource(new StringReader(xml)), logger);
}
}
Output:
start order id=7
start item sku=A1 qty=2
text "Pen"
end item
start item sku=B2 qty=1
text "Notebook "
text "&"
text " cover"
end item
end order
- Each element produces a
with its attributes and a matchingstartElement . The parser keeps no memory of earlier events, so the handler tracks depth itself.endElement - The text "Notebook & cover" arrived as three
calls, split at the entity. The SAX specification allows the parser to deliver text in any number of chunks, also at buffer boundaries in large files. Handlers must collect text in acharacters and use it inStringBuilder , never assume one call per element.endElement - Attribute values come already unescaped.
Namespaces in SAX
The three name parameters of startElement
import java.io.StringReader;
import javax.xml.parsers.SAXParserFactory;
import org.xml.sax.Attributes;
import org.xml.sax.InputSource;
import org.xml.sax.helpers.DefaultHandler;
public class SaxNamespaces {
public static void main(String[] args) throws Exception {
String xml = """
<s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/">
<s:Body><price xmlns="urn:shop">9.50</price></s:Body>
</s:Envelope>""";
for (boolean aware : new boolean[] {false, true}) {
SAXParserFactory f = SAXParserFactory.newInstance();
f.setNamespaceAware(aware);
System.out.println("namespaceAware=" + aware);
f.newSAXParser().parse(new InputSource(new StringReader(xml)), new DefaultHandler() {
@Override
public void startPrefixMapping(String prefix, String uri) {
System.out.println(" prefix mapping: '" + prefix + "' -> " + uri);
}
@Override
public void startElement(String uri, String local, String qName,
Attributes atts) {
System.out.printf(" start uri=[%s] localName=[%s] qName=[%s]%n", uri,
local, qName);
}
});
}
}
}
Output:
namespaceAware=false
start uri=[] localName=[] qName=[s:Envelope]
start uri=[] localName=[] qName=[s:Body]
start uri=[] localName=[] qName=[price]
namespaceAware=true
prefix mapping: 's' -> http://schemas.xmlsoap.org/soap/envelope/
start uri=[http://schemas.xmlsoap.org/soap/envelope/] localName=[Envelope] qName=[s:Envelope]
start uri=[http://schemas.xmlsoap.org/soap/envelope/] localName=[Body] qName=[s:Body]
prefix mapping: '' -> urn:shop
start uri=[urn:shop] localName=[price] qName=[price]
is not namespace-aware by default. With awareness off,SAXParserFactory anduri were empty strings, and onlylocalName , the name as written including its prefix, carried information.qName- With
, each element came with its namespace URI and local name, andsetNamespaceAware(true) reported each declaration before the element that declares it, including the default namespace (empty prefix) onstartPrefixMapping .<price> - Handlers written against
break when a sender picks another prefix, such asqName instead ofsoap: . Turn namespace awareness on and match ons: plusuri .localName
Building objects from nested elements
Turning SAX events into Java objects needs two pieces of state: which elements are currently open, and the text collected so far. The order document reuses the element name <name>
import java.io.StringReader;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Deque;
import java.util.List;
import javax.xml.parsers.SAXParserFactory;
import org.xml.sax.Attributes;
import org.xml.sax.InputSource;
import org.xml.sax.helpers.DefaultHandler;
public class SaxToObjects {
record Line(String sku, int qty) {
}
record Order(String id, String customer, List<Line> lines) {
}
// Builds records from nested elements, using a stack of open element names
static class OrderHandler extends DefaultHandler {
final List<Order> orders = new ArrayList<>();
private final Deque<String> path = new ArrayDeque<>();
private final StringBuilder text = new StringBuilder();
private String id;
private String customer;
private String sku;
private List<Line> lines;
@Override
public void startElement(String uri, String local, String qName, Attributes atts) {
path.push(local);
text.setLength(0);
switch (local) {
case "order" -> {
id = atts.getValue("id");
lines = new ArrayList<>();
}
case "line" -> sku = atts.getValue("sku");
default -> { }
}
}
@Override
public void characters(char[] ch, int start, int length) {
text.append(ch, start, length);
}
@Override
public void endElement(String uri, String local, String qName) {
path.pop();
String parent = path.peek();
switch (local) {
case "name" -> {
if ("customer".equals(parent)) { // <name> also exists elsewhere
customer = text.toString().trim();
}
}
case "qty" -> lines.add(new Line(sku, Integer.parseInt(text.toString().trim())));
case "order" -> orders.add(new Order(id, customer, List.copyOf(lines)));
default -> { }
}
}
}
public static void main(String[] args) throws Exception {
String xml = """
<orders>
<order id="o1">
<customer><name>Ana</name></customer>
<line sku="A1"><name>Pen</name><qty>2</qty></line>
<line sku="B2"><name>Pad</name><qty>1</qty></line>
</order>
<order id="o2">
<customer><name>Ben</name></customer>
<line sku="C3"><name>Ink</name><qty>5</qty></line>
</order>
</orders>""";
SAXParserFactory f = SAXParserFactory.newInstance();
f.setNamespaceAware(true);
f.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true);
OrderHandler h = new OrderHandler();
f.newSAXParser().parse(new InputSource(new StringReader(xml)), h);
h.orders.forEach(System.out::println);
}
}
Output:
Order[id=o1, customer=Ana, lines=[Line[sku=A1, qty=2], Line[sku=B2, qty=1]]]
Order[id=o2, customer=Ben, lines=[Line[sku=C3, qty=5]]]
- A
used as a stack holds the open element names:Deque pushes,startElement pops. After popping,endElement is the parent, so apath.peek() inside<name> sets the customer, while the product names Pen, Pad and Ink were ignored.<customer> - Attributes are read in
, because they are only available there: the order id and each line's SKU.startElement - Objects are completed in
, when all their parts have arrived: aendElement whenLine closes, an<qty> whenOrder closes. The result is the same two orders a DOM program would produce, without ever holding the document in memory.<order>
Stopping early, and handling errors
SAX has no method to stop parsing, and its error handling has a default that hides problems. The program searches a document of 500,000 users for the first admin, then parses a malformed document and a document that breaks a schema rule.
import java.io.ByteArrayInputStream;
import java.io.StringReader;
import java.nio.charset.StandardCharsets;
import javax.xml.XMLConstants;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import javax.xml.transform.stream.StreamSource;
import javax.xml.validation.SchemaFactory;
import org.xml.sax.Attributes;
import org.xml.sax.InputSource;
import org.xml.sax.Locator;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;
import org.xml.sax.helpers.DefaultHandler;
public class SaxStopAndErrors {
// SAX has no "stop" method: throwing an exception from a callback ends the parse
static class FoundIt extends SAXException {
final String value;
FoundIt(String value) {
super("found");
this.value = value;
}
}
static class FindFirst extends DefaultHandler {
int elements;
String found;
@Override
public void startElement(String uri, String local, String qName, Attributes atts)
throws SAXException {
elements++;
if (qName.equals("user") && "admin".equals(atts.getValue("role"))) {
throw new FoundIt(atts.getValue("name"));
}
}
}
// Records validation errors; DefaultHandler's error() would ignore them
static class Collecting extends DefaultHandler {
private Locator locator;
int errors;
@Override
public void setDocumentLocator(Locator l) {
locator = l;
}
@Override
public void startElement(String uri, String local, String qName, Attributes atts) {
if (qName.equals("qty")) {
System.out.println(" <qty> starts at line " + locator.getLineNumber());
}
}
@Override
public void error(SAXParseException e) {
errors++;
System.out.println(" error() line " + e.getLineNumber() + ": " + e.getMessage());
}
}
static long time(SAXParser p, byte[] xml, DefaultHandler h) throws Exception {
long t0 = System.nanoTime();
try {
p.parse(new ByteArrayInputStream(xml), h);
} catch (FoundIt e) {
if (h instanceof FindFirst ff) {
ff.found = e.value;
}
}
return (System.nanoTime() - t0) / 1000000;
}
public static void main(String[] args) throws Exception {
StringBuilder sb = new StringBuilder("<users>");
for (int i = 0; i < 500000; i++) {
sb.append("<user name=\"u").append(i).append("\" role=\"")
.append(i == 1000 ? "admin" : "user").append("\"/>");
}
byte[] xml = sb.append("</users>").toString().getBytes(StandardCharsets.UTF_8);
SAXParserFactory f = SAXParserFactory.newInstance();
SAXParser p = f.newSAXParser();
time(p, xml, new FindFirst()); // warm-up
FindFirst stop = new FindFirst();
long early = time(p, xml, stop);
System.out.println("found " + stop.found + ", stopped after " + stop.elements
+ " elements: " + early + " ms");
DefaultHandler all = new DefaultHandler();
System.out.println("parsing all 500,001 elements: " + time(p, xml, all) + " ms");
// A broken document: fatalError, with the line and column
try {
p.parse(new InputSource(new StringReader("<a>\n<b>text</a>")), new DefaultHandler());
} catch (SAXParseException e) {
System.out.println("malformed: line " + e.getLineNumber() + ", column "
+ e.getColumnNumber() + ": " + e.getMessage());
}
// Validation errors are not fatal and reach error(), which DefaultHandler ignores
String xsd = """
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
<xs:element name="order"><xs:complexType><xs:sequence>
<xs:element name="qty" type="xs:positiveInteger"/>
</xs:sequence></xs:complexType></xs:element>
</xs:schema>""";
String bad = "<order>\n <qty>-3</qty>\n</order>";
SAXParserFactory vf = SAXParserFactory.newInstance();
vf.setNamespaceAware(true);
vf.setSchema(SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI)
.newSchema(new StreamSource(new StringReader(xsd))));
vf.newSAXParser().parse(new InputSource(new StringReader(bad)), new DefaultHandler());
System.out.println("with plain DefaultHandler: parse finished, no exception");
Collecting c = new Collecting();
vf.newSAXParser().parse(new InputSource(new StringReader(bad)), c);
System.out.println("with error() overridden: " + c.errors + " errors reported");
}
}
Output:
found u1000, stopped after 1002 elements: 19 ms
parsing all 500,001 elements: 542 ms
malformed: line 2, column 10: The element type "b" must be terminated by the matching end-tag "</b>".
with plain DefaultHandler: parse finished, no exception
<qty> starts at line 2
error() line 2: cvc-minInclusive-valid: Value '-3' is not facet-valid with respect to minInclusive '1' for type 'positiveInteger'.
error() line 2: cvc-type.3.1.3: The value '-3' of element 'qty' is not valid.
with error() overridden: 2 errors reported
- Throwing a
subclass from a callback ends the parse at once. The admin was user 1000, so the parser stopped after 1,002 elements and finished in milliseconds, many times faster than the full parse. On a server that searches large feeds for one record, this is the main advantage of a streaming parser after memory. The exception carries the found value back to the caller.SAXException - Malformed XML is a fatal error:
threwparse with line 2, column 10 and a precise message. The parser cannot continue after a fatal error.SAXParseException - The trap: a schema violation, here
for a-3 , is a non-fatal error, andpositiveInteger does nothing. With the plain handler, parsing finished without any exception. OverridingDefaultHandler.error() reported both messages; rethrowing the exception there is the usual way to make validation strict.error() gives asetDocumentLocator that reports the current line during callbacks, which is how a handler can include positions in its own error messages.Locator
Processing a file larger than the heap
The program writes a 48 MB file with one million <sale>
import java.io.BufferedWriter;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Map;
import java.util.TreeMap;
import javax.xml.XMLConstants;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
public class SaxAggregate {
// Totals sales per region from a file of any size, keeping only the totals in memory
static class SalesHandler extends DefaultHandler {
final Map<String, Double> totals = new TreeMap<>();
final StringBuilder text = new StringBuilder();
String region;
int sales;
@Override
public void startElement(String uri, String local, String qName, Attributes a) {
if (qName.equals("sale")) {
region = a.getValue("region");
}
text.setLength(0); // characters() may arrive in pieces
}
@Override
public void characters(char[] ch, int start, int length) {
text.append(ch, start, length);
}
@Override
public void endElement(String uri, String local, String qName) throws SAXException {
if (qName.equals("amount")) {
totals.merge(region, Double.parseDouble(text.toString().trim()), Double::sum);
sales++;
}
}
}
public static void main(String[] args) throws Exception {
Path file = Files.createTempFile("sales", ".xml");
String[] regions = {"north", "south", "east", "west"};
try (BufferedWriter w = Files.newBufferedWriter(file)) {
w.write("<sales>\n");
for (int i = 0; i < 1000000; i++) {
w.write(" <sale region=\"" + regions[i % 4] + "\"><amount>" + (i % 100) / 10.0
+ "</amount></sale>\n");
}
w.write("</sales>\n");
}
System.out.println("file size: " + Files.size(file) / (1024 * 1024) + " MB");
SAXParserFactory f = SAXParserFactory.newInstance();
f.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true);
f.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
SAXParser parser = f.newSAXParser();
Runtime rt = Runtime.getRuntime();
SalesHandler h = new SalesHandler();
parser.parse(file.toFile(), h);
System.out.printf("parsed %,d sales with a heap limit of %d MB%n", h.sales,
rt.maxMemory() / (1024 * 1024));
h.totals.forEach((r, t) -> System.out.printf(" %-5s %,12.1f%n", r, t));
// The same file as a DOM tree does not fit in this heap
try {
var doc = javax.xml.parsers.DocumentBuilderFactory.newInstance()
.newDocumentBuilder().parse(file.toFile());
System.out.println("DOM: parsed " + doc.getDocumentElement().getChildNodes()
.getLength() + " nodes");
} catch (OutOfMemoryError e) {
System.out.println("DOM with the same heap: OutOfMemoryError (" + e.getMessage()
+ ")");
}
Files.delete(file);
}
}
Output (run with -Xmx32m
file size: 48 MB
parsed 1,000,000 sales with a heap limit of 32 MB
east 1,250,000.0
north 1,200,000.0
south 1,225,000.0
west 1,275,000.0
DOM with the same heap: OutOfMemoryError (Java heap space)
Only four totals and one text buffer were ever in memory, so the heap limit was no obstacle for SAX. The DOM parser, given the same 32 MB, failed with OutOfMemoryError
remembers what is needed from attributes (the region) and clears the text buffer;startElement appends to the buffer;characters uses the complete text when the element it belongs to closes.endElement
The factory also disallows DOCTYPE
| Setting | Effect |
|---|---|
setFeature("http://apache.org/xml/features/disallow-doctype-decl", true) | Rejects any document with a DOCTYPE |
setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true) | Applies the JDK's limits on entity expansion, nesting depth and attribute counts |
setXIncludeAware(false) | Keeps XInclude, which can also pull in other files, switched off (the default) |
An EntityResolver | For documents that must keep a DOCTYPE |
Constant memory does not make parsing free: every byte of the 48 MB still has to be read and tokenized, so for long-running parses a counter in the handler that logs progress every few thousand records is worth adding.
SAX, StAX or DOM?
| Situation | Use |
|---|---|
| Huge file, a few element types of interest, read once | SAX |
| Huge file, logic that reads better as a loop, or early exit | |
| Writing large XML | StAX's XMLStreamWriter |
| Small document, random access or editing | |
| Queries by path | |
| Validating against a schema while streaming | SAX with setSchemaerror() |
| Libraries built on SAX, such as many XML-to-object tools | SAX, because they expect a ContentHandler |
Both SAX and StAX stream with constant memory. With SAX the parser drives and state lives in fields; with StAX your code drives with an ordinary loop and can stop with a break