Java 怎么使用javax.xml.stream.xmlstreamreader接口读取文档

2019年7月29日20:58:28Java 怎么使用javax.xml.stream.xmlstreamreader接口读取文档已关闭评论 1,625 1304字阅读4分20秒

1.简介

Java 怎么使用javax.xml.stream.xmlstreamreader接口读取文档?——请看下文。

2.示例代码

/**
 * 版权所有 编程十万个怎么办(www.tah1986.com)
 */
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;
      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();
    }
  }
}

 
继续阅读
编程十万个怎么办