Java Reference
In-Depth Information
Java provides several ways to read XML documents. One way is to use StAX, a
streaming model. It is better than the older SAX API because it allows you to both read
and write XML documents. Although StAX is not quite as powerful as a DOM API, it
is an excellent and efficient API that is less taxing on memory resources.
StAX provides two methods for reading XML documents: a cursor API and an iter-
ator API. The cursor-oriented API utilizes a cursor that can walk an XML document
from start to finish, pointing to one element at a time, and always moving forward. The
iterator API represents an XML document stream as a set of discrete event objects,
provided in the order that they are read in the source XML. The event-oriented, iterator
API is preferred over the cursor API at this time because it provides XMLEvent ob-
jects with the following benefits:
The XMLEvent objects are immutable and can persist even though the
StAX parser has moved on to subsequent events. You can pass these
XMLEvent objects to other processes or store them in lists, arrays, and
maps.
You can subclass XMLEvent , creating your own specialized events as
needed.
You can modify the incoming event stream by adding or removing
events, which is more flexible than the cursor API.
To use StAX to read documents, create an XML event reader on your file input
stream. Check that events are still available with the hasNext() method and read
each event using the nextEvent() method. The nextEvent() method will return
a specific type of XMLEvent that corresponds to the start and stop elements, attrib-
utes, and value data in the XML file. Remember to close your readers and file streams
when you're finished with those objects.
You can invoke the example application like this, using the patients.xml file
as your <xmlFile> argument:
java org.java8recipes.chapter20.recipe20_2.DocReader
<xmlFile>
20-3. Transforming XML
Problem
Search WWH ::




Custom Search