StAX parser was created to address limitations in the two most prevalent parsing APIs, SAX and DOM. The primary goal of the StAX API is to give "parsing control to the programmer by exposing a simple iterator based API. This allows the programmer to ask for the next event (pull the event) and allows state to be stored in procedural fashion."
To use StAX parser, you should have stax.jar in your application's classpath. Download stax-1.2.0.jar from here:
StAX enables you to create bidirectional XML parsers that are fast. It proves a better alternative to other methods, such as DOM and SAX, both in terms of performance and usability
The DOM model involves creating in-memory objects representing an entire document tree and the complete infoset state for an XML document. Once in memory, DOM trees can be navigated freely and parsed arbitrarily, and as such provide maximum flexibility for developers. However, the cost of this flexibility is a potentially large memory footprint and significant processor requirements.
Streaming model in which XML infosets are transmitted and parsed serially at application runtime, often in real time, and often from dynamic sources whose contents are not precisely known beforehand. Moreover, stream-based parsers can start generating output immediately, and infoset elements can be discarded and garbage collected immediately after they are used.
Streaming models for XML processing are particularly useful when your application has strict memory limitations, as with a cellphone running the Java Platform, Micro Edition (Java ME platform), or when your application needs to process several requests simultaneously, as with an application server. In fact, it can be argued that the majority of XML business logic can benefit from stream processing, and does not require the in-memory maintenance of entire DOM trees.
|API Type||Pull, streaming||Push, streaming||In memory tree|
|Ease of Use||High||Medium||High|
|CPU and Memory Efficiency||Good||Good||Varies|
|Create, Read, Update, Delete||No||No||Yes|
In this example we will parse book.xml using Stax parser and populate object of corresponding class with parsed data. The xml which we are going to parse is given below:
I made 2 class to hold parsed data of book.xml are given below:
In next step I created my Stax parser class BookStaxParser.java. Source of BookStaxParser.java is given below:
Here is Main class from where I am intiating stax parsing.