Skip to content

Instantly share code, notes, and snippets.

@Crydust
Last active August 30, 2023 14:03
Show Gist options
  • Save Crydust/2bfea12cd358b2b69112b8cac7aec5d1 to your computer and use it in GitHub Desktop.
Save Crydust/2bfea12cd358b2b69112b8cac7aec5d1 to your computer and use it in GitHub Desktop.
Read xml using stax api in java
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.List;
import javax.xml.namespace.QName;
import javax.xml.stream.XMLEventReader;
import javax.xml.stream.XMLInputFactory;
import javax.xml.stream.events.EndElement;
import javax.xml.stream.events.StartElement;
import javax.xml.stream.events.XMLEvent;
public class XmlStax {
public static void main(String[] args) throws Exception {
try (InputStream in = Files.newInputStream(Path.of("sample.xml"))) {
XMLEventReader reader = XMLInputFactory.newInstance().createXMLEventReader(in);
while (reader.hasNext()) {
XMLEvent nextEvent = reader.nextEvent();
if (nextEvent.isStartElement()) {
StartElement startElement = nextEvent.asStartElement();
String elementName = startElement.getName().getLocalPart();
if ("FOO".equals(elementName)) {
String attr = startElement.getAttributeByName(QName.valueOf("xxx")).getValue();
}
}
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment