background image

cursor2event Sample

<< Returning String Representations | Creating an Event Iterator >>
<< Returning String Representations | Creating an Event Iterator >>
CURSOR
2
EVENT
S
AMPLE
­ C
URSOR
A
PPROACH
E
VENT
O
BJECT
.
JAVA
105
return "SPACE";
}
return"UNKNOWN_EVENT_TYPE , "+ eventType;
}
Running the Sample
When you run the
CursorParse
sample, the class is compiled, and the XML
stream is parsed and returned to
STDOUT
.
cursor2event Sample ­
CursorApproachEventObject.java
Located
in
the
<javaee.tutorial.home>/examples/stax/cursor2event
directory,
CursorApproachEventObject.java
demonstrates how to get infor-
mation returned by an
XMLEvent
object even when using the cursor API.
The idea here is that the cursor API's
XMLStreamReader
returns integer con-
stants corresponding to particular events, where as the event iterator API's
XMLEventReader
returns immutable and persistent event objects.
XMLStream-
Reader
is more efficient, but
XMLEventReader
is easier to use, as all the informa-
tion related to a particular event is encapsulated in a returned
XMLEvent
object.
However, the disadvantage of event approach is the extra overhead of creating
objects for every event, which consumes both time and memory.
With this mind,
XMLEventAllocator
can be used to get event information as an
XMLEvent object, even when using the cursor API.
Instantiating an XMLEventAllocator
The first step is to create a new
XMLInputFactory
and instantiate an
XMLEven-
tAllocator
:
XMLInputFactory xmlif = XMLInputFactory.newInstance();
System.out.println("FACTORY: " + xmlif);
xmlif.setEventAllocator(new XMLEventAllocatorImpl());
allocator = xmlif.getEventAllocator();
XMLStreamReader xmlr = xmlif.createXMLStreamReader(filename,
new FileInputStream(filename));