XMLEventReader Demo : Streaming XML Parser « JDK 6 « Java

XMLEventReader Demo


import java.io.FileReader;
import java.io.Reader;
import java.util.Iterator;

import javax.xml.namespace.QName;
import javax.xml.stream.XMLEventReader;
import javax.xml.stream.XMLInputFactory;
import javax.xml.stream.events.Attribute;
import javax.xml.stream.events.Characters;
import javax.xml.stream.events.EndElement;
import javax.xml.stream.events.StartElement;
import javax.xml.stream.events.XMLEvent;

public class XMLEventReaderDemo {
  public static void main(String[] args) throws Exception {
    XMLInputFactory factory = XMLInputFactory.newInstance();
    Reader fileReader = new FileReader("Source.xml");
    XMLEventReader reader = factory.createXMLEventReader(fileReader);

    while (reader.hasNext()) {
      XMLEvent event = reader.nextEvent();
      if (event.isStartElement()) {
        StartElement element = (StartElement) event;
        System.out.println("Start Element: " + element.getName());

        Iterator iterator = element.getAttributes();
        while (iterator.hasNext()) {
          Attribute attribute = (Attribute) iterator.next();
          QName name = attribute.getName();
          String value = attribute.getValue();
          System.out.println("Attribute name/value: " + name + "/" + value);
      if (event.isEndElement()) {
        EndElement element = (EndElement) event;
        System.out.println("End element:" + element.getName());
      if (event.isCharacters()) {
        Characters characters = (Characters) event;
        System.out.println("Text: " + characters.getData());


Related examples in the same category

1.Stax XML iterator read
2.Stax XML cursor read
3.StAX is a technology similar to SAX.
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