Use the XMLEventReader to read and process events using an event-oriented interface. - Java XML

Java examples for XML:XMLEventReader

Description

Use the XMLEventReader to read and process events using an event-oriented interface.

Demo Code

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("c:/test.xml")) {
      reader = factory.createXMLEventReader(fis);
      boolean inName = false;
      boolean inDiagnosis = false;
      String id = null;//from w w  w . ja v a  2 s  .  com
      String name = null;
      String diagnosis = 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 "patient":
            id = startElement.getAttributeByName(QName.valueOf("id"))
                .getValue();
            break;
          case "name":
            inName = true;
            break;
          case "diagnosis":
            inDiagnosis = true;
            break;
          default:
            break;
          }
          break;
        case XMLEvent.END_ELEMENT:
          EndElement endElement = event.asEndElement();
          elementName = endElement.getName().getLocalPart();
          if (elementName.equals("patient")) {
            System.out.printf("Patient: %s\nName: %s\nDiagnosis: %s\n\n", id,
                name, diagnosis);
            id = name = diagnosis = null;
            inName = inDiagnosis = false;
          }
          break;
        case XMLEvent.CHARACTERS:
          String value = event.asCharacters().getData();
          if (inName) {
            name = value;
            inName = false;
          } else if (inDiagnosis) {
            diagnosis = value;
            inDiagnosis = false;
          }
          break;
        }
      }
    }
    if (reader != null) {
      reader.close();
    }
  }
}

Related Tutorials