Java Reference
In-Depth Information
on the
iterator design pattern
(see
http://sourcemaking.com/
design_patterns/iterator
)
, which results in an application that
is easier to write and debug. In contrast, SAX adopts the
push model
, in
which the parser passes infoset items via events to the application, wheth-
er or not the application is ready to receive them. This model is based
on the
observer design pattern
(see
http://sourcemaking.com/
design_patterns/observer
)
,whichresultsinanapplicationthatis
often harder to write and debug.
Summing up, StAX can parse or create documents of arbitrary size, makes infoset
itemsavailabletoapplicationsalmostimmediately,andusesthepullmodeltoputthe
application in charge. Neither SAX nor DOM offers all these advantages.
Java implements StAX through types stored in the
javax.xml.stream
,
javax.xml.stream.events
, and
javax.xml.stream.util
packages. This
sectionintroducesyoutovarioustypesfromthefirsttwopackageswhileshowingyou
how to use StAX to parse and create XML documents.
STREAM-BASED VERSUS EVENT-BASED READERS AND WRITERS
StAX parsers are known as
document readers
, and StAX document creators are
knownas
document writers
.StAXclassifiesdocumentreadersanddocumentwriters
as stream-based or event-based.
A
stream-based reader
extractsthenextinfosetitemfromaninputstreamviaa
curs-
or
(infosetitempointer).Similarly,astream-basedwriterwritesthenextinfosetitem
toanoutputstreamatthecursorposition.Thecursorcanpointtoonlyoneitemata
time, and always moves forward, typically by one infoset item.
Stream-based readers and writers are appropriate when writing code for memory-
constrainedenvironmentssuchasJavaME,becauseyoucanusethemtocreatesmal-
lerandmoreefficientcode.Theyalsoofferbetterperformanceforlow-levellibrar-
ies, where performance is important.
An event-based reader extracts the next infoset item from an input stream by ob-
taininganevent.Similarly,anevent-basedwriterwritesthenextinfosetitemtothe
stream by adding an event to the output stream. In contrast to stream-based readers
and writers, event-based readers and writers have no concept of a cursor.
Event-based readers and writers are appropriate for creating
XML processing
pipelines
(sequences of components that transform the previous component's input
andpassthetransformedoutputtothenextcomponentinthesequence),formodify-
ing an event sequence, and more.