StAX is a technology similar to SAX. : Streaming XML Parser « JDK 6 « Java






StAX is a technology similar to SAX.

 
import java.io.FileReader;
import java.io.Reader;

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

public class XMLStreamReaderDemo {
  public static void main(String[] args) throws Exception {
    XMLInputFactory factory = XMLInputFactory.newInstance();

    Reader fileReader = new FileReader("source.xml");
    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;
    }
  }
}

        








Related examples in the same category

1.Stax XML iterator read
2.Stax XML cursor read
3.XMLEventReader Demo
4.XMLStreamWriter Demo
5.Using XMLEventFactory to create xml document
6.Streaming XML Parser: Stax Event
7.Streaming XML Parser: Stax Event Filter
8.XMLEventReader and XMLEventWriter for Stax XML parser
9.Using XMLStreamWriter to create XML file
10.STAX cursor
11.Catch XMLStreamException
12.Get information as an XMLEvent object when using cursor approach