Last active
August 30, 2023 14:03
-
-
Save Crydust/2bfea12cd358b2b69112b8cac7aec5d1 to your computer and use it in GitHub Desktop.
Read xml using stax api in java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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