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.

Share

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 returns, the parser forgets that element; it never builds a tree. Memory use therefore stays constant however large the file is, and parsing is fast because no node objects are created. The other side is that the parser drives: your code cannot ask "what is the parent of this element?", so a handler that needs context must remember it in fields.

SAX 2.0 dates from 2000 and has been in the JDK since Java 1.4, through JAXP's SAXParserFactory in the java.xml module. The callbacks are split across several interfaces, and DefaultHandler implements all of them with empty methods, so you override only what you need.

The main SAX callbacks
CallbackInterfaceCalled for
startDocument, endDocumentContentHandlerThe start and end of the input
startElement, endElementContentHandlerEach start and end tag, with attributes on the start
charactersContentHandlerText, in one or more chunks
startPrefixMappingContentHandlerNamespace declarations
setDocumentLocatorContentHandlerOnce, giving an object that reports the current line and column
warning, error, fatalErrorErrorHandlerProblems; only fatalError stops parsing by default
resolveEntityEntityResolverExternal entities and DTDs, where XXE attacks start

SAXParser is a thin wrapper around an XMLReader, the lower-level SAX interface that getXMLReader() returns. The reader lets you set the content, error and entity handlers separately, and chain XMLFilters that sit between the parser and your handler, each seeing and passing on the events. Neither a parser nor a reader is thread-safe, and a handler holds per-document state, so create a new parser and handler for each document, or keep one per thread. Creating a parser from an existing factory is cheap.

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 & on purpose.

Java
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 &amp; 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:

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 startElement with its attributes and a matching endElement. The parser keeps no memory of earlier events, so the handler tracks depth itself.
  • The text "Notebook & cover" arrived as three characters 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 a StringBuilder and use it in endElement, never assume one call per element.
  • Attribute values come already unescaped.

Namespaces in SAX

The three name parameters of startElement are filled differently depending on one factory setting. The program parses a small SOAP envelope, a format that always uses namespaces, with namespace awareness off and on.

Java
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:

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]
  • SAXParserFactory is not namespace-aware by default. With awareness off, uri and localName were empty strings, and only qName, the name as written including its prefix, carried information.
  • With setNamespaceAware(true), each element came with its namespace URI and local name, and startPrefixMapping reported each declaration before the element that declares it, including the default namespace (empty prefix) on <price>.
  • Handlers written against qName break when a sender picks another prefix, such as soap: instead of s:. Turn namespace awareness on and match on uri plus 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> for both the customer and each product, which a handler that only looks at the current element name would confuse.

Java
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:

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 Deque used as a stack holds the open element names: startElement pushes, endElement pops. After popping, path.peek() is the parent, so a <name> inside <customer> sets the customer, while the product names Pen, Pad and Ink were ignored.
  • Attributes are read in startElement, because they are only available there: the order id and each line's SKU.
  • Objects are completed in endElement, when all their parts have arrived: a Line when <qty> closes, an Order when <order> closes. The result is the same two orders a DOM program would produce, without ever holding the document in memory.

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.

Java
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:

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 SAXException 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.
  • Malformed XML is a fatal error: parse threw SAXParseException with line 2, column 10 and a precise message. The parser cannot continue after a fatal error.
  • The trap: a schema violation, here -3 for a positiveInteger, is a non-fatal error, and DefaultHandler.error() does nothing. With the plain handler, parsing finished without any exception. Overriding error() reported both messages; rethrowing the exception there is the usual way to make validation strict.
  • setDocumentLocator gives a Locator that reports the current line during callbacks, which is how a handler can include positions in its own error messages.

Processing a file larger than the heap

The program writes a 48 MB file with one million <sale> records across four regions and totals the amounts per region, then tries to load the same file with DOM. It runs with the heap limited to 32 MB, smaller than the file. The amounts cycle through 0.0 to 9.9, so each region's expected total can be worked out by hand: north, for example, gets every fourth record and totals 1,200,000.

Java
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):

Output
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: a tree of this file needs several times its size, as measured on the DOM parser page. The pattern in the handler is the standard one:

  1. startElement remembers what is needed from attributes (the region) and clears the text buffer;
  2. characters appends to the buffer;
  3. endElement uses the complete text when the element it belongs to closes.

The factory also disallows DOCTYPE, which blocks the external entity attack described on the DOM page; SAX parsers resolve external entities by default too. The settings that matter for untrusted input are the same as for DOM:

Hardening a SAXParserFactory
SettingEffect
setFeature("http://apache.org/xml/features/disallow-doctype-decl", true)Rejects any document with a DOCTYPE, which stops XXE and entity bombs before they start
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 that returns empty inputFor documents that must keep a DOCTYPE: no external file or URL is ever read

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?

Choosing a streaming or tree API
SituationUse
Huge file, a few element types of interest, read onceSAX
Huge file, logic that reads better as a loop, or early exitStAX
Writing large XMLStAX's XMLStreamWriter; SAX cannot write
Small document, random access or editingDOM
Queries by pathXPath over a DOM
Validating against a schema while streamingSAX with setSchema and an error() that throws
Libraries built on SAX, such as many XML-to-object toolsSAX, 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.