background image

Reading Attributes

<< XMLStreamReader Methods | Writing XML Streams >>
<< XMLStreamReader Methods | Writing XML Streams >>
94
S
TREAMING
API
FOR
XML
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.StartEle-
ment
, 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
.
Reading Namespaces
Similar to reading attributes, namespaces are read using an
Iterator
created by
calling the
getNamespaces()
method on the
StartElement
interface. Only the
namespace for the current
StartElement
is returned, and an application can get