Java 怎么使用XMLEventReader读取和处理面向事件的接口

2019年7月29日21:00:02Java 怎么使用XMLEventReader读取和处理面向事件的接口已关闭评论 828 1601字阅读5分20秒

1.简介

Java 怎么使用XMLEventReader读取和处理面向事件的接口?——请看下文。

2.示例代码

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

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