Java XMLEventReader read xml file
import java.io.FileInputStream; 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 Main { public static void main(String[] args) throws Exception { XMLInputFactory factory = XMLInputFactory.newFactory(); XMLEventReader reader = null; try (FileInputStream fis = new FileInputStream("xmlFile.xml")) { reader = factory.createXMLEventReader(fis); boolean inName = false; boolean inFeature = false; String id = null;/* w w w . j a v a 2 s.co m*/ String name = null; String feature = null; while (reader.hasNext()) { XMLEvent event = reader.nextEvent(); String elementName = null; switch (event.getEventType()) { case XMLEvent.START_ELEMENT: StartElement startElement = event.asStartElement(); elementName = startElement.getName().getLocalPart(); switch (elementName) { case "language": id = startElement.getAttributeByName(QName.valueOf("id")).getValue(); break; case "name": inName = true; break; case "feature": inFeature = true; break; default: break; } break; case XMLEvent.END_ELEMENT: EndElement endElement = event.asEndElement(); elementName = endElement.getName().getLocalPart(); if (elementName.equals("language")) { System.out.printf("Language: %s\nName: %s\nFeature: %s\n\n", id, name, feature); id = name = feature = null; inName = inFeature = false; } break; case XMLEvent.CHARACTERS: String value = event.asCharacters().getData(); if (inName) { name = value; inName = false; } else if (inFeature) { feature = value; inFeature = false; } break; } } } if (reader != null) { reader.close(); } } }