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.
Code
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
Dotenv File ParserParse .env file content into a JSON object, handling comments, export prefixes, single quotes, and double-quoted escape sequences.INI File ParserParse INI configuration files into nested JSON with section objects, global keys, and both semicolon and hash comment support.JSON to TOML ConverterTurn a JSON object into TOML, emitting nested objects as tables and arrays of objects as array-of-tables blocks.JSON to YAML ConverterConvert JSON to readable YAML with nested block mappings, sequences, and quoting only where it is required.
FAQ
- What does StAX XMLStreamReader Pull Parsing print when run?
- The script runs standalone; its 3 labeled outputs include `start`, `text`, `end`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.