background image

Cursor-to-Event Example

<< Returning String Representations | Creating the Allocator Method >>
<< Returning String Representations | Creating the Allocator Method >>

Cursor-to-Event Example

6. In the Projects tab, right-click the cursor project and select Properties. The Project
Properties dialog is displayed.
7. Enter the following in the Arguments field:
-x 1 BookCatalog.xml
8. Click OK.
9. Right-click the cursor project and select Run Project.
Building and Running the Cursor Example Using Ant
To compile and run the Cursor example using Ant, in a terminal window, go to the
tut-install/javaeetutorial5/examples/stax/cursor/ directory and type the following:
ant run-cursor
Cursor-to-Event Example
Located in the tut-install/javaeetutorial5/examples/stax/cursor2event/ directory,
CursorApproachEventObject.java
demonstrates how to get information returned by an
XMLEvent
object even when using the cursor API.
The idea here is that the cursor API's XMLStreamReader returns integer constants
corresponding to particular events, while the event iterator API's XMLEventReader returns
immutable and persistent event objects. XMLStreamReader is more efficient, but
XMLEventReader
is easier to use, because all the information 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 XMLEventAllocator:
XMLInputFactory xmlif = XMLInputFactory.newInstance();
System.out.println(
"FACTORY: " + xmlif);
xmlif.setEventAllocator(new XMLEventAllocatorImpl());
allocator = xmlif.getEventAllocator();
XMLStreamReader xmlr = xmlif.createXMLStreamReader(filename,
new FileInputStream(filename));
Creating an Event Iterator
The next step is to create an event iterator:
Example Code
Chapter 18 · Streaming API for XML
571