Java StAX Parser: XMLStreamReader and XMLStreamWriter Examples

StAX is the streaming XML API in which your code pulls the next event when it is ready, instead of the parser pushing events to callbacks. That gives constant memory like SAX, with code that reads like an ordinary loop and can stop as soon as it has what it needs. StAX also writes XML. This page explains the pull model, runs both StAX APIs, combines StAX with DOM for large files, and measures StAX against SAX and DOM.

Share

Contents

How StAX works

StAX (Streaming API for XML, JSR 173, in the JDK since Java 6) is a pull parser. A SAX parser reads the whole input and calls your code for each event; a StAX reader does nothing until your code asks for the next event. The reader is a cursor that sits on one event at a time, such as a start tag, a piece of text or an end tag, and methods like getLocalName() and getAttributeValue() describe that event. Because your code controls the loop, it can call helper methods for sub-elements, keep state in local variables, and simply stop reading when it has what it needs. Memory stays constant, as with SAX.

StAX has two reading styles and matching writers, all created from factories in javax.xml.stream:

The StAX APIs
APIStyleBest for
XMLStreamReaderCursor: next() returns an int event typeMost reading code; creates no event objects
XMLEventReaderIterator of XMLEvent objects, with peek()Looking ahead, filtering, passing events around
XMLStreamWriterMethod calls: writeStartElement, writeCharactersWriting large documents in constant memory
XMLEventWriterAccepts XMLEvent objectsCopying a document while changing parts of it

The event types are constants in XMLStreamConstants: START_ELEMENT (1), END_ELEMENT (2), CHARACTERS (4), COMMENT, START_DOCUMENT, END_DOCUMENT and a few more. All programs use only the JDK and were run on JDK 21.

Reading with XMLStreamReader

The program builds a document with 10,000 users and looks for the user with id 42, stopping as soon as it is found. A helper reads that user's child elements with two convenience methods: nextTag() skips whitespace and moves to the next start or end tag, and getElementText() reads the text of a text-only element and moves past its end tag.

Java
import java.io.StringReader;
import javax.xml.stream.XMLInputFactory;
import javax.xml.stream.XMLStreamConstants;
import javax.xml.stream.XMLStreamReader;

public class StaxRead {

    static XMLInputFactory safeFactory() {
        XMLInputFactory f = XMLInputFactory.newInstance();
        f.setProperty(XMLInputFactory.SUPPORT_DTD, false);              // blocks XXE
        f.setProperty(XMLInputFactory.IS_SUPPORTING_EXTERNAL_ENTITIES, false);
        return f;
    }

    public static void main(String[] args) throws Exception {
        StringBuilder xml = new StringBuilder("<users>");
        for (int i = 1; i <= 10000; i++) {
            xml.append("<user id=\"").append(i).append("\"><name>user").append(i)
                    .append("</name><email>u").append(i).append("@example.com</email></user>");
        }
        xml.append("</users>");

        // Pull parsing: our loop asks for the next event, so it can stop whenever it likes
        XMLStreamReader r = safeFactory().createXMLStreamReader(new StringReader(xml.toString()));
        int events = 0;
        String found = null;
        while (r.hasNext() && found == null) {
            int event = r.next();
            events++;
            if (event == XMLStreamConstants.START_ELEMENT && r.getLocalName().equals("user")
                    && r.getAttributeValue(null, "id").equals("42")) {
                found = readUser(r);
            }
        }
        r.close();
        System.out.println("found: " + found);
        System.out.println("events read before stopping: " + events
                + " (the document has 10,000 users)");
    }

    // Reads the children of the current <user> element; getElementText reads a text-only element
    static String readUser(XMLStreamReader r) throws Exception {
        String name = null;
        String email = null;
        while (r.nextTag() == XMLStreamConstants.START_ELEMENT) {
            switch (r.getLocalName()) {
                case "name" -> name = r.getElementText();
                case "email" -> email = r.getElementText();
                default -> throw new IllegalStateException("unexpected " + r.getLocalName());
            }
        }
        return name + " <" + email + ">";
    }
}

Output:

Output
found: user42 <u42@example.com>
events read before stopping: 330 (the document has 10,000 users)

Each user produces 8 events (start, text and end for name and email, plus the start and end of user). After 41 users and the root, the 42nd user's start tag is event 330, and the loop ended there; the remaining 9,958 users were never parsed. With SAX, stopping early requires throwing an exception from a callback; with StAX it is a loop condition.

The factory turns off DTD support, which prevents the external entity (XXE) attack shown on the DOM parser page. The StAX defaults allow DTDs, as the next program confirms, so set this for any input you do not control.

Text, CDATA and namespaces

Two details decide whether StAX code reads text correctly: text can arrive in several events, and namespaces are handled differently from DOM and SAX. The invoice note contains an entity and a CDATA section, the usual places where text gets split, and uses a default namespace.

Java
import java.io.StringReader;
import javax.xml.stream.XMLInputFactory;
import javax.xml.stream.XMLStreamConstants;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamReader;

public class StaxDetails {

    static final String XML = """
            <inv:invoice xmlns:inv="urn:example:invoice" xmlns="urn:example:common">
              <note>Fish &amp; chips <![CDATA[<cheap>]]> today</note>
            </inv:invoice>""";

    static void dump(XMLInputFactory f, String label) throws XMLStreamException {
        System.out.println(label);
        XMLStreamReader r = f.createXMLStreamReader(new StringReader(XML));
        while (r.hasNext()) {
            int ev = r.next();
            switch (ev) {
                case XMLStreamConstants.START_ELEMENT -> System.out.println("  START "
                        + r.getPrefix() + ":" + r.getLocalName() + " ns=" + r.getNamespaceURI()
                        + " (declares " + r.getNamespaceCount() + ")");
                case XMLStreamConstants.CHARACTERS, XMLStreamConstants.CDATA -> {
                    if (!r.isWhiteSpace()) {
                        System.out.println("  " + (ev == XMLStreamConstants.CDATA ? "CDATA" :
                                "CHARACTERS") + " [" + r.getText() + "]");
                    }
                }
                default -> { }
            }
        }
        r.close();
    }

    public static void main(String[] args) throws Exception {
        XMLInputFactory f = XMLInputFactory.newInstance();
        f.setProperty(XMLInputFactory.SUPPORT_DTD, false);
        System.out.println("defaults: namespaceAware=" + f.getProperty(
                XMLInputFactory.IS_NAMESPACE_AWARE) + ", coalescing="
                + f.getProperty(XMLInputFactory.IS_COALESCING) + ", supportDTD(default)="
                + XMLInputFactory.newInstance().getProperty(XMLInputFactory.SUPPORT_DTD));
        dump(f, "default factory:");
        f.setProperty(XMLInputFactory.IS_COALESCING, true);
        dump(f, "IS_COALESCING = true:");

        // getElementText() collects all text of a text-only element for you
        XMLStreamReader r = XMLInputFactory.newInstance()
                .createXMLStreamReader(new StringReader(XML));
        r.nextTag();
        r.nextTag();
        System.out.println("getElementText(): [" + r.getElementText() + "]");

        // getElementText() refuses mixed content
        XMLStreamReader m = XMLInputFactory.newInstance()
                .createXMLStreamReader(new StringReader("<p>Hello <b>you</b></p>"));
        m.nextTag();
        try {
            m.getElementText();
        } catch (XMLStreamException e) {
            System.out.println("getElementText() on mixed content: "
                    + e.getClass().getSimpleName() + ", START_ELEMENT found inside <p>");
        }
    }
}

Output:

Output
defaults: namespaceAware=true, coalescing=false, supportDTD(default)=true
default factory:
  START inv:invoice ns=urn:example:invoice (declares 2)
  START :note ns=urn:example:common (declares 0)
  CHARACTERS [Fish ]
  CHARACTERS [&]
  CHARACTERS [ chips ]
  CHARACTERS [<cheap>]
  CHARACTERS [ today]
IS_COALESCING = true:
  START inv:invoice ns=urn:example:invoice (declares 2)
  START :note ns=urn:example:common (declares 0)
  CHARACTERS [Fish & chips <cheap> today]
getElementText(): [Fish & chips <cheap> today]
getElementText() on mixed content: XMLStreamException, START_ELEMENT found inside <p>
  • Unlike DocumentBuilderFactory and SAXParserFactory, XMLInputFactory is namespace-aware by default. The unprefixed <note> correctly reported the default namespace urn:example:common, and getNamespaceCount() showed the 2 declarations on the root.
  • By default, the text "Fish & chips <cheap> today" arrived as 5 separate CHARACTERS events, split at the entity and at the CDATA section. The JDK's reader reported the CDATA as ordinary characters. Code that takes one getText() per element gets only "Fish ".
  • IS_COALESCING made the reader join adjacent text into one event. getElementText() also returns the full text, whatever the setting, so it is the safest way to read text-only elements.
  • getElementText() throws an XMLStreamException for mixed content, text with child elements inside it such as a paragraph containing a <b> element; there you must loop over the events yourself, appending text and handling each child.

The event API: peek, filters and rewriting

XMLEventReader returns each event as an object, which makes three things easy: looking at the next event before consuming it, filtering events, and copying events to a writer. The document holds two users with passwords, so the last part can show a streaming rewrite that removes sensitive data.

Java
import java.io.StringReader;
import java.io.StringWriter;
import javax.xml.stream.XMLEventFactory;
import javax.xml.stream.XMLEventReader;
import javax.xml.stream.XMLEventWriter;
import javax.xml.stream.XMLInputFactory;
import javax.xml.stream.XMLOutputFactory;
import javax.xml.stream.events.StartElement;
import javax.xml.stream.events.XMLEvent;

public class EventApi {

    static final String XML = "<users><user id=\"1\"><name>Ana</name><password>s3cret</password>"
            + "</user><user id=\"2\"><name>Ben</name><password>hunter2</password></user></users>";

    public static void main(String[] args) throws Exception {
        XMLInputFactory in = XMLInputFactory.newInstance();
        in.setProperty(XMLInputFactory.SUPPORT_DTD, false);

        // peek() looks at the next event without consuming it
        XMLEventReader r = in.createXMLEventReader(new StringReader(XML));
        while (r.hasNext()) {
            XMLEvent e = r.nextEvent();
            if (e.isStartElement() && e.asStartElement().getName().getLocalPart().equals("name")
                    && r.peek().isCharacters()) {
                System.out.println("name: " + r.peek().asCharacters().getData());
            }
        }

        // A filtered reader only delivers the events the filter accepts
        XMLEventReader starts = in.createFilteredReader(in.createXMLEventReader(
                new StringReader(XML)), XMLEvent::isStartElement);
        StringBuilder names = new StringBuilder();
        while (starts.hasNext()) {
            names.append(((StartElement) starts.nextEvent()).getName().getLocalPart())
                    .append(' ');
        }
        System.out.println("start elements only: " + names.toString().trim());

        // Copy events to a writer, dropping <password> and renaming <user> to <member>
        StringWriter out = new StringWriter();
        XMLEventWriter w = XMLOutputFactory.newInstance().createXMLEventWriter(out);
        XMLEventFactory ef = XMLEventFactory.newInstance();
        XMLEventReader copy = in.createXMLEventReader(new StringReader(XML));
        int skipDepth = 0;
        while (copy.hasNext()) {
            XMLEvent e = copy.nextEvent();
            if (e.isStartElement() && e.asStartElement().getName().getLocalPart()
                    .equals("password")) {
                skipDepth++;
            }
            if (skipDepth == 0) {
                if (e.isStartElement() && e.asStartElement().getName().getLocalPart()
                        .equals("user")) {
                    StartElement s = e.asStartElement();
                    e = ef.createStartElement("", "", "member", s.getAttributes(), null);
                } else if (e.isEndElement() && e.asEndElement().getName().getLocalPart()
                        .equals("user")) {
                    e = ef.createEndElement("", "", "member");
                }
                w.add(e);
            }
            if (e.isEndElement() && e.asEndElement().getName().getLocalPart()
                    .equals("password")) {
                skipDepth--;
            }
        }
        w.close();
        System.out.println("rewritten: " + out);
    }
}

Output:

Output
name: Ana
name: Ben
start elements only: users user name password user name password
rewritten: <?xml version="1.0" ?><users><member id="1"><name>Ana</name></member><member id="2"><name>Ben</name></member></users>
  • peek() showed the text after each <name> start without moving past it, so the loop could check that it really was text before using it.
  • createFilteredReader with XMLEvent::isStartElement delivered only start elements, 7 of them, in document order.
  • Copying events to an XMLEventWriter rewrote the document in one pass: every <password> and its content was dropped, and <user> became <member> with its id attribute kept. This works on files of any size, because only the current event is in memory.
  • Event objects cost an allocation each, so the cursor API is the better default when you do not need these features. An XMLEventReader can also be built on top of an existing XMLStreamReader with createXMLEventReader(streamReader), so code can switch styles in the middle of a document.

Streaming a large file, record by record into DOM

A common need is a huge feed of records that are each small but awkward to read event by event. StAX can find each record, and the JDK's Transformer can copy just that element into a small DOM tree through a StAXSource. The feed has three orders with nested lines; the first loop below has a bug that is easy to write.

Java
import java.io.StringReader;
import javax.xml.stream.XMLInputFactory;
import javax.xml.stream.XMLStreamConstants;
import javax.xml.stream.XMLStreamReader;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMResult;
import javax.xml.transform.stax.StAXSource;
import org.w3c.dom.Element;

public class StaxToDom {

    static void report(Element order) {
        int qty = 0;
        var lines = order.getElementsByTagName("line");
        for (int i = 0; i < lines.getLength(); i++) {
            qty += Integer.parseInt(((Element) lines.item(i)).getAttribute("qty"));
        }
        System.out.println("  order " + order.getAttribute("id") + " for "
                + order.getElementsByTagName("customer").item(0).getTextContent() + ": "
                + lines.getLength() + " lines, total qty " + qty);
    }

    // Streams through the feed, but turns each <order> into a small DOM tree
    static void process(String xml, boolean checkCurrent) throws Exception {
        XMLInputFactory f = XMLInputFactory.newInstance();
        f.setProperty(XMLInputFactory.SUPPORT_DTD, false);
        XMLStreamReader r = f.createXMLStreamReader(new StringReader(xml));
        Transformer copy = TransformerFactory.newInstance().newTransformer();
        int event = r.getEventType();
        while (true) {
            if (event == XMLStreamConstants.START_ELEMENT && r.getLocalName().equals("order")) {
                DOMResult result = new DOMResult();
                copy.transform(new StAXSource(r), result);   // consumes the whole <order>
                report((Element) result.getNode().getFirstChild());
                if (checkCurrent) {
                    event = r.getEventType();                // already on the next event
                    continue;
                }
            }
            if (!r.hasNext()) {
                break;
            }
            event = r.next();
        }
    }

    public static void main(String[] args) throws Exception {
        StringBuilder sb = new StringBuilder("<feed>");
        for (int i = 1; i <= 3; i++) {
            sb.append("<order id=\"").append(i).append("\"><customer>c").append(i)
                    .append("</customer><lines><line qty=\"").append(i).append("\"/>")
                    .append("<line qty=\"").append(i * 10).append("\"/></lines></order>");
        }
        String xml = sb.append("</feed>").toString();

        System.out.println("naive loop:");
        process(xml, false);
        System.out.println("loop that checks the current event first:");
        process(xml, true);
    }
}

Output:

Output
naive loop:
  order 1 for c1: 2 lines, total qty 11
  order 3 for c3: 2 lines, total qty 33
loop that checks the current event first:
  order 1 for c1: 2 lines, total qty 11
  order 2 for c2: 2 lines, total qty 22
  order 3 for c3: 2 lines, total qty 33
  • Each order became a DOM element, so getElementsByTagName("line") and getAttribute could total its quantities (1 + 10 = 11 for order 1). Only one order's tree exists at a time, so memory stays constant however long the feed is.
  • The naive loop lost order 2. transform consumes the whole <order> element and leaves the reader on the next event, which here was order 2's start tag. The loop then called next() and moved past it.
  • The fixed loop reads getEventType() after the transform and examines the current event before calling next(). The same care is needed after getElementText() and after any helper method that reads ahead.

Writing with XMLStreamWriter

XMLStreamWriter writes XML as a sequence of calls, also in constant memory, which suits large exports. The item names in the program contain &, quotes and angle brackets to show how they are escaped.

Java
import java.io.StringWriter;
import javax.xml.stream.XMLOutputFactory;
import javax.xml.stream.XMLStreamWriter;

public class StaxWrite {

    record Item(String sku, int qty, String name) {
    }

    public static void main(String[] args) throws Exception {
        Item[] items = {new Item("A1", 2, "Pen"), new Item("B2", 1, "Notebook & \"cover\""),
            new Item("C3", 5, "Clips <small>")};

        StringWriter out = new StringWriter();
        XMLStreamWriter w = XMLOutputFactory.newInstance().createXMLStreamWriter(out);
        w.writeStartDocument("UTF-8", "1.0");
        w.writeStartElement("order");
        w.writeDefaultNamespace("urn:example:orders");
        w.writeAttribute("id", "7");
        for (Item it : items) {
            w.writeStartElement("item");
            w.writeAttribute("sku", it.sku());
            w.writeAttribute("qty", Integer.toString(it.qty()));
            w.writeCharacters(it.name());              // escaped automatically
            w.writeEndElement();
        }
        w.writeEmptyElement("note");
        w.writeEndElement();
        w.writeEndDocument();
        w.close();

        // The writer does not indent; split after each tag only for display
        System.out.println(out.toString().replace("><", ">\n<"));
    }
}

Output (line breaks added after each tag for display):

Output
<?xml version="1.0" encoding="UTF-8"?>
<order xmlns="urn:example:orders" id="7">
<item sku="A1" qty="2">Pen</item>
<item sku="B2" qty="1">Notebook &amp; "cover"</item>
<item sku="C3" qty="5">Clips &lt;small&gt;</item>
<note/>
</order>
  • writeCharacters escaped &, < and >. Quotes do not need escaping in element text; in attribute values the writer escapes them.
  • writeDefaultNamespace adds the xmlns declaration to the current element.
  • writeEmptyElement writes a self-closing tag with no matching end call.
  • The writer does not check that every start has an end, and it does not indent. Call writeEndDocument, which closes any open elements, and pretty-print separately if you need it.

StAX, SAX and DOM compared

The program sums the <total> of 100,000 orders in a 7.8 MB document with each of the three APIs. The three alternate over 5 rounds; the first 2 are warm-up and the best of the remaining 3 is shown. This is a rough comparison on a 2-CPU Linux machine with JDK 21.

Java
import java.io.ByteArrayInputStream;
import java.nio.charset.StandardCharsets;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.SAXParserFactory;
import javax.xml.stream.XMLInputFactory;
import javax.xml.stream.XMLStreamConstants;
import javax.xml.stream.XMLStreamReader;
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import org.xml.sax.Attributes;
import org.xml.sax.helpers.DefaultHandler;

public class XmlSpeed {

    interface Sum {
        double run(byte[] xml) throws Exception;
    }

    static double stax(byte[] xml) throws Exception {
        XMLStreamReader r = XMLInputFactory.newInstance()
                .createXMLStreamReader(new ByteArrayInputStream(xml));
        double sum = 0;
        while (r.hasNext()) {
            if (r.next() == XMLStreamConstants.START_ELEMENT
                    && r.getLocalName().equals("total")) {
                sum += Double.parseDouble(r.getElementText());
            }
        }
        return sum;
    }

    static double sax(byte[] xml) throws Exception {
        double[] sum = {0};
        SAXParserFactory.newInstance().newSAXParser().parse(new ByteArrayInputStream(xml),
                new DefaultHandler() {
                    private final StringBuilder text = new StringBuilder();
                    private boolean inTotal;

                    @Override
                    public void startElement(String u, String l, String q, Attributes a) {
                        inTotal = q.equals("total");
                        text.setLength(0);
                    }

                    @Override
                    public void characters(char[] ch, int start, int len) {
                        if (inTotal) {
                            text.append(ch, start, len);
                        }
                    }

                    @Override
                    public void endElement(String u, String l, String q) {
                        if (q.equals("total")) {
                            sum[0] += Double.parseDouble(text.toString());
                            inTotal = false;
                        }
                    }
                });
        return sum[0];
    }

    static double dom(byte[] xml) throws Exception {
        Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder()
                .parse(new ByteArrayInputStream(xml));
        NodeList totals = doc.getElementsByTagName("total");
        double sum = 0;
        for (int i = 0; i < totals.getLength(); i++) {
            sum += Double.parseDouble(totals.item(i).getTextContent());
        }
        return sum;
    }

    public static void main(String[] args) throws Exception {
        StringBuilder sb = new StringBuilder("<orders>\n");
        for (int i = 0; i < 100000; i++) {
            sb.append("  <order id=\"").append(i).append("\"><customer>user").append(i % 1000)
                    .append("</customer><total>").append(i % 500).append(".25</total></order>\n");
        }
        byte[] xml = sb.append("</orders>\n").toString().getBytes(StandardCharsets.UTF_8);
        System.out.printf("document: 100,000 orders, %.1f MB%n", xml.length / 1e6);

        String[] names = {"StAX XMLStreamReader", "SAX DefaultHandler",
            "DOM + getElementsByTagName"};
        Sum[] ways = {XmlSpeed::stax, XmlSpeed::sax, XmlSpeed::dom};
        long[] best = {Long.MAX_VALUE, Long.MAX_VALUE, Long.MAX_VALUE};
        double[] result = new double[3];
        for (int round = 0; round < 5; round++) {        // rounds 0 and 1 are warm-up
            for (int i = 0; i < ways.length; i++) {
                long t0 = System.nanoTime();
                result[i] = ways[i].run(xml);
                long t = System.nanoTime() - t0;
                if (round >= 2) {
                    best[i] = Math.min(best[i], t);
                }
            }
        }
        for (int i = 0; i < ways.length; i++) {
            System.out.printf("%-27s sum %,.2f  %4d ms%n", names[i], result[i],
                    best[i] / 1000000);
        }
    }
}

Output of the parser comparison:

Output
document: 100,000 orders, 7.8 MB
StAX XMLStreamReader        sum 24,975,000.00    39 ms
SAX DefaultHandler          sum 24,975,000.00    36 ms
DOM + getElementsByTagName  sum 24,975,000.00   110 ms
  • All three produced the same sum. StAX and SAX were close to each other, and neither was ahead in every run on this machine. In the JDK both sit on the same Xerces scanner (the StAX reader is com.sun.org.apache.xerces.internal.impl.XMLStreamReaderImpl), so they do almost the same work per byte.
  • DOM took roughly two to three times as long, because it creates an object for every node before the program can look at any of them, and it needs memory in proportion to the document.
  • The choice between StAX and SAX is therefore about code style rather than speed: StAX for loops, helper methods and early exit, SAX where a library expects a ContentHandler.

Which one to use

Choosing an XML API
SituationUse
Large file, read once, simple loop or early exitXMLStreamReader
Large file, need to look ahead or filter eventsXMLEventReader
Large file of small records that are awkward to streamStAX to find each record, StAXSource into DOM
Rewriting a large document on the flyXMLEventReader plus XMLEventWriter
Writing large XMLXMLStreamWriter
Callback-based librariesSAX
Small documents to navigate or editDOM and XPath
Documents with a fixed schema mapped to classesJAXB, which can also unmarshal from an XMLStreamReader