background image

Using XMLEventReader

<< XMLStreamReader Methods | Writing XML Streams >>
<< XMLStreamReader Methods | Writing XML Streams >>

Using XMLEventReader

XMLInputFactory f = XMLInputFactory.newInstance();
XMLStreamReader r = f.createXMLStreamReader( ... );
while(r.hasNext()) {
r.next();
}
Using XMLEventReader
The XMLEventReader API in the StAX event iterator API provides the means to map events in
an XML stream to allocated event objects that can be freely reused, and the API itself can be
extended to handle custom events.
XMLEventReader
provides four methods for iteratively parsing XML streams:
next
: Returns the next event in the stream
nextEvent
: Returns the next typed XMLEvent
hasNext
: Returns true if there are more events to process in the stream
peek
: Returns the event but does not iterate to the next event
For example, the following code snippet illustrates the XMLEventReader method declarations:
package javax.xml.stream;
import java.util.Iterator;
public interface XMLEventReader extends Iterator {
public Object next();
public XMLEvent nextEvent() throws XMLStreamException;
public boolean hasNext();
public XMLEvent peek() throws XMLStreamException;
...
}
To read all events on a stream and then print them, you could use the following:
while(stream.hasNext()) {
XMLEvent event = stream.nextEvent();
System.out.print(event);
}
Reading Attributes
You can access attributes from their associated javax.xml.stream.StartElement, as follows:
public interface StartElement extends XMLEvent {
public Attribute getAttributeByName(QName name);
public Iterator getAttributes();
}
You can use the getAttributes method on the StartElement interface to use an Iterator
over all the attributes declared on that StartElement.
Using StAX
Chapter 18 · Streaming API for XML
563