Java Reference
In-Depth Information
The high-level
XMLEventReader
interface offers a somewhat less efficient but
more object-oriented way to read XML data with StAX. This interface's
boolean
hasNext()
method returns true when there is a next event to obtain; otherwise,
it returns false. The
XMLEvent nextEvent()
method returns the next event as
an object whose class implements a subinterface of the
javax.xml.stream.events.XMLEvent
interface.
Note
XMLEvent
isthebaseinterfaceforhandlingmarkupevents.Itdeclaresmeth-
odsthatapplytoallsubinterfaces; forexample,
Location getLocation()
(re-
turn a
javax.xml.stream.Location
object whose
int getCharacter-
Offset()
and other methods return location information about the event) and
int
getEventType()
(return the event type as an
XMLStreamConstants
infoset
constant, such as
START_ELEMENT
and
PROCESSING_INSTRUCTION
—
XMLEvent
extends
XMLStreamConstants
).
XMLEvent
issubtypedbyother
javax.xml.stream.events
interfacesthatde-
scribe different kinds of events (e.g.,
Attribute
) in terms of methods that return
infoset item-specific information (such as
Attribute
's
QName getName()
and
String getValue()
methods).
Thefollowingexampleusesthe
hasNext()
and
nextEvent()
methodstocodify
a parsing loop that detects the start and end of an element:
while (xmler.hasNext())
{
switch (xmler.nextEvent().getEventType())
{
case XMLEvent.START_ELEMENT: // Do something at ele-
ment start.
break;
case XMLEvent.END_ELEMENT : // Do something at ele-
ment end.
}
}
XML document's start and end elements via an event-based reader.
Listing 10-17.
StAXDemo
(version 2)