Java Reference
In-Depth Information
ateXMLStreamReader(Reader reader)
. These methods throw
javax.xml.stream.XMLStreamException
whenthestream-basedreadercan-
not be created.
The following example creates a stream-based reader whose source is a file named
recipe.xml
:
Reader reader = new FileReader("recipe.xml");
XMLStreamReader
xmlsr
=
xm-
lif.createXMLStreamReader(reader);
The low-level
XMLStreamReader
interface offers the most efficient way to read
XML data with StAX. This interface's
boolean hasNext()
method returns true
whenthereisanextinfosetitemtoobtain;otherwise,itreturnsfalse.The
int next()
methodadvancesthecursorbyoneinfosetitemandreturnsanintegercodethatidenti-
fies this item's type.
Instead of comparing
next()
's return value with an integer value, you would
compare this value against a
javax.xml.stream.XMLStreamConstants
in-
fosetconstant,suchas
START_ELEMENT
or
DTD
—
XMLStreamReader
extendsthe
XMLStreamConstants
interface.
Note
You can also obtain the type of the infoset item that the cursor is pointing
to by calling
XMLStreamReader
's
int getEventType()
method. Specifying
“
Event
”inthenameofthismethodisunfortunatebecauseitconfusesstream-based
readers with event-based readers.
Thefollowingexampleusesthe
hasNext()
and
next()
methodstocodifyapars-
ing loop that detects the start and end of each element:
while (xmlsr.hasNext())
{
switch (xmlsr.next())
{
case XMLStreamReader.START_ELEMENT: // Do something
at element start.
break;
case XMLStreamReader.END_ELEMENT : // Do something
at element end.
}
}