Reading an XML File - Java XML

Java examples for XML:XMLStreamReader

Introduction

Use the javax.xml.stream.XMLStreamReader interface to read documents.

Demo Code

import java.io.FileInputStream;

import javax.xml.stream.XMLInputFactory;
import javax.xml.stream.XMLStreamConstants;
import javax.xml.stream.XMLStreamReader;

public class Main {

  public static void main(String[] args) throws Exception {
    XMLInputFactory factory = XMLInputFactory.newFactory();
    try (FileInputStream fis = new FileInputStream("c:/test.xml")) {
      XMLStreamReader reader = factory.createXMLStreamReader(fis);
      boolean inName = false;
      boolean inDiagnosis = false;
      String id = null;// ww  w  . j  a  va2  s .c  o  m
      String name = null;
      String diagnosis = null;

      while (reader.hasNext()) {
        int event = reader.next();
        switch (event) {
        case XMLStreamConstants.START_ELEMENT:
          String elementName = reader.getLocalName();
          switch (elementName) {
          case "patient":
            id = reader.getAttributeValue(0);
            break;
          case "name":
            inName = true;
            break;
          case "diagnosis":
            inDiagnosis = true;
            break;
          default:
            break;
          }
          break;
        case XMLStreamConstants.END_ELEMENT:
          String elementname = reader.getLocalName();
          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 XMLStreamConstants.CHARACTERS:
          if (inName) {
            name = reader.getText();
            inName = false;
          } else if (inDiagnosis) {
            diagnosis = reader.getText();
            inDiagnosis = false;
          }
          break;
        default:
          break;
        }
      }
      reader.close();
    }
  }
}

Related Tutorials