background image

Stepping Through Events

<< Sample XML Document | Returning String Representations >>
<< Sample XML Document | Returning String Representations >>
CURSOR
S
AMPLE
­ C
URSOR
P
ARSE
.
JAVA
103
cursor Sample ­ CursorParse.java
Located in the
<javaee.tutorial.home>/examples/stax/cursor
directory,
CursorParse.java
demonstrates using the StAX cursor API to read an XML
document. In this sample, the application instructs the parser to read the next
event in the XML input stream by calling
<code>next()</code>
.
Note that
<code>next()</code>
just returns an integer constant corresponding
to underlying event where the parser is positioned. The application needs to call
the relevant function to get more information related to the underlying event.
You can imagine this approach as a virtual cursor moving across the XML input
stream. There are various accessor methods which can be called when that vir-
tual cursor is at particular event.
Stepping Through Events
In this example, the client application pulls the next event in the XML stream by
calling the
next()
method on the parser; for example:
try
{
for(int i =0 ; i< count ; i++)
{
//pass the file name.. allrelativeentity
//references will be resolved againstthis as
//base URI.
XMLStreamReader xmlr=
xmlif.createXMLStreamReader(filename, new
FileInputStream(filename));
//when XMLStreamReader is created, it is positioned
at START_DOCUMENT event.
int eventType = xmlr.getEventType();
//printEventType(eventType);
printStartDocument(xmlr);
//check if there aremore eventsinthe input stream
while(xmlr.hasNext())
{
eventType =xmlr.next();
//printEventType(eventType);
//these functionsprints the information about
theparticular event by calling relevant function
printStartElement(xmlr);
printEndElement(xmlr);
printText(xmlr);