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.
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()getAttributeValue()
StAX has two reading styles and matching writers, all created from factories in javax.xml.stream
| API | Style | Best for |
|---|---|---|
XMLStreamReader | Cursor: next()int | Most reading code; creates no event objects |
XMLEventReader | Iterator of XMLEventpeek() | Looking ahead, filtering, passing events around |
XMLStreamWriter | Method calls: writeStartElementwriteCharacters | Writing large documents in constant memory |
XMLEventWriter | Accepts XMLEvent | Copying a document while changing parts of it |
The event types are constants in XMLStreamConstantsSTART_ELEMENTEND_ELEMENTCHARACTERSCOMMENTSTART_DOCUMENTEND_DOCUMENT
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()getElementText()
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:
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 nameemailuser
The factory turns off DTD support, which prevents the external entity (XXE) attack shown on the
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.
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 & 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:
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
andDocumentBuilderFactory ,SAXParserFactory is namespace-aware by default. The unprefixedXMLInputFactory correctly reported the default namespace<note> , andurn:example:common showed the 2 declarations on the root.getNamespaceCount() - By default, the text "Fish & chips <cheap> today" arrived as 5 separate
events, split at the entity and at the CDATA section. The JDK's reader reported the CDATA as ordinary characters. Code that takes oneCHARACTERS per element gets only "Fish ".getText() made the reader join adjacent text into one event.IS_COALESCING also returns the full text, whatever the setting, so it is the safest way to read text-only elements.getElementText() throws angetElementText() for mixed content, text with child elements inside it such as a paragraph containing aXMLStreamException element; there you must loop over the events yourself, appending text and handling each child.<b>
The event API: peek, filters and rewriting
XMLEventReader
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:
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>
showed the text after eachpeek() start without moving past it, so the loop could check that it really was text before using it.<name> withcreateFilteredReader delivered only start elements, 7 of them, in document order.XMLEvent::isStartElement- Copying events to an
rewrote the document in one pass: everyXMLEventWriter and its content was dropped, and<password> became<user> with its<member> attribute kept. This works on files of any size, because only the current event is in memory.id - Event objects cost an allocation each, so the cursor API is the better default when you do not need these features. An
can also be built on top of an existingXMLEventReader withXMLStreamReader , so code can switch styles in the middle of a document.createXMLEventReader(streamReader)
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 TransformerStAXSource
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:
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
andgetElementsByTagName("line") 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.getAttribute - The naive loop lost order 2.
consumes the wholetransform element and leaves the reader on the next event, which here was order 2's start tag. The loop then called<order> and moved past it.next() - The fixed loop reads
after the transform and examines the current event before callinggetEventType() . The same care is needed afternext() and after any helper method that reads ahead.getElementText()
Writing with XMLStreamWriter
XMLStreamWriter&
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):
<?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 & "cover"</item>
<item sku="C3" qty="5">Clips <small></item>
<note/>
</order>
escapedwriteCharacters ,& and< . Quotes do not need escaping in element text; in attribute values the writer escapes them.> adds thewriteDefaultNamespace declaration to the current element.xmlns writes a self-closing tag with no matching end call.writeEmptyElement- The writer does not check that every start has an end, and it does not indent. Call
, which closes any open elements, and pretty-print separately if you need it.writeEndDocument
StAX, SAX and DOM compared
The program sums the <total>
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:
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
), so they do almost the same work per byte.com.sun.org.apache.xerces.internal.impl.XMLStreamReaderImpl - 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
| Situation | Use |
|---|---|
| Large file, read once, simple loop or early exit | XMLStreamReader |
| Large file, need to look ahead or filter events | XMLEventReader |
| Large file of small records that are awkward to stream | StAX to find each record, StAXSource |
| Rewriting a large document on the fly | XMLEventReaderXMLEventWriter |
| Writing large XML | XMLStreamWriter |
| Callback-based libraries | |
| Small documents to navigate or edit | |
| Documents with a fixed schema mapped to classes | XMLStreamReader |