background image

Stepping through Events

<< Example XML Document | Returning String Representations >>
<< Example XML Document | Returning String Representations >>

Stepping through Events

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 virtual cursor is at a 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.. all relative entity
// references will be resolved against this 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 are more events in the input stream
while(xmlr.hasNext()) {
eventType = xmlr.next();
printEventType(eventType);
// these functions print the information about
// the particular event by calling the relevant
// function
printStartElement(xmlr);
printEndElement(xmlr);
printText(xmlr);
printPIData(xmlr);
printComment(xmlr);
}
}
}
Note that next just returns an integer constant corresponding to the event underlying the
current cursor location. The application calls the relevant function to get more information
related to the underlying event. There are various accessor methods which can be called when
the cursor is at particular event.
Example Code
Chapter 18 · Streaming API for XML
569