StAX

The Streaming API for XML (StAX) is a parsing model intermediate between DOM and SAX. Its entry point is a cursor that represents a position within the document. The application moves the cursor forward, "pulling" data from the parser as needed - the opposite of SAX, which "pushes" data to the application by invoking callbacks and requires the application to maintain whatever state is needed to track its position within the document.

Because the application drives iteration explicitly, StAX code can read like an ordinary loop, and the application only needs to keep the state relevant to what it is currently doing - it can stop reading at any point, or skip over uninteresting sections, without processing the whole document. Like SAX, StAX does not build an in-memory document tree, so its memory footprint stays low, but its pull model is generally considered easier to follow than SAX's callback-driven model.

StAX is defined for Java by JSR 173 and has been part of the standard library since Java SE 6, in the javax.xml.stream package. Its two central interfaces are XMLStreamReader, a low-level cursor API, and XMLEventReader, a higher-level API that returns one XMLEvent object per step. StAX is a specific instance of the more general pull parsing pattern.

Full nameStreaming API for XML
Processing modelCursor-based streaming, pull-based
Defined byJSR 173 (Java); part of the standard library since Java SE 6
Key interfacesXMLStreamReader (cursor API), XMLEventReader (iterator API)
ContrastThe application pulls data from the parser, unlike SAX's push model

XMLInputFactory factory = XMLInputFactory.newInstance();
XMLStreamReader reader = factory.createXMLStreamReader(new FileInputStream("books.xml"));

while (reader.hasNext()) {
    int event = reader.next();
    if (event == XMLStreamConstants.START_ELEMENT && reader.getLocalName().equals("book")) {
        System.out.println("Book id: " + reader.getAttributeValue(null, "id"));
    }
}
reader.close();