App下載
首頁(yè)javastaxJava HTML/XML - 如何使用Stax解析器解析XML

Java HTML/XML - 如何使用Stax解析器解析XML

我們想知道如何使用Stax解析器解析XML。

import java.io.Reader;
import java.io.StringReader;

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

public class Main {
  public static String getXMLData(){
    return "<x></x>";
  }
  public static void main(String[] args) throws Exception {
    XMLInputFactory factory = XMLInputFactory.newInstance();

    Reader fileReader = new StringReader(getXMLData());
    XMLStreamReader reader = factory.createXMLStreamReader(fileReader);

    while (reader.hasNext()) {
      process(reader);
      reader.next();
    }
  }
  private static void process(XMLStreamReader reader) {
    int eventType = reader.getEventType();
    switch (eventType) {
    case XMLStreamConstants.START_ELEMENT:
      System.out.println("Start element: " + reader.getLocalName());

      int count = reader.getAttributeCount();
      for (int i = 0; i < count; i++) {
        String name = reader.getAttributeLocalName(i);
        String value = reader.getAttributeValue(i);
        System.out.println("\tAttribute name/value: " + name + "/" + value);
      }
      break;

    case XMLStreamConstants.END_ELEMENT:
      System.out.println("End element: " + reader.getLocalName());
      break;

    case XMLStreamConstants.CHARACTERS:
      System.out.println("Text: " + reader.getText());
      break;
    default:
      break;
    }
  }
}