StAX XMLStreamReader Pull Parsing

Walk an XML document with the StAX XMLStreamReader cursor, dispatching on START_ELEMENT, CHARACTERS, and END_ELEMENT events as you pull them.

JavaConfig Management

Code

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

public class StaxXmlStreamReaderPullParse {

    public static void main(String[] args) throws XMLStreamException {
        String xml = """
                <config version="2">
                    <server host="db.internal" port="5432"/>
                    <retry max="3">exponential</retry>
                </config>""";

        // StAX 拉式解析(pull parsing):游标由调用方推进,事件逐一返回
        XMLStreamReader reader = XMLInputFactory.newInstance()
                .createXMLStreamReader(new StringReader(xml));

        while (reader.hasNext()) {
            switch (reader.next()) {
                case XMLStreamReader.START_ELEMENT -> {
                    StringBuilder attrs = new StringBuilder();
                    for (int i = 0; i < reader.getAttributeCount(); i++) {
                        attrs.append(reader.getAttributeLocalName(i))
                                .append('=')
                                .append(reader.getAttributeValue(i))
                                .append(' ');
                    }
                    System.out.println("start  " + reader.getLocalName() + "  " + attrs.toString().trim());
                }
                case XMLStreamReader.CHARACTERS -> {
                    if (!reader.isWhiteSpace()) {
                        System.out.println("text   " + reader.getText().trim());
                    }
                }
                case XMLStreamReader.END_ELEMENT ->
                        System.out.println("end    " + reader.getLocalName());
                default -> { }
            }
        }
        reader.close();
    }
}

What the code does

Under the hood: the class StaxXmlStreamReaderPullParse.

The file repeats itself only inside while (reader.hasNext()).

Caveats

  • Copy, run: the standard library answers every call in the file.

Applying it

The run emits 3 labeled sections — start, text, end — one per step.

Load-bearing statements

XMLStreamReader reader = XMLInputFactory.newInstance()
        .createXMLStreamReader(new StringReader(xml));
attrs.append(reader.getAttributeLocalName(i))
        .append('=')
        .append(reader.getAttributeValue(i))
        .append(' ');
StringBuilder attrs = new StringBuilder();

Interactive Tools for This Topic

FAQ

What does StAX XMLStreamReader Pull Parsing print when run?
The script runs standalone; its 3 labeled outputs include `start`, `text`, `end`.