Stax parser

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."

Environment setup for stax

To use StAX parser, you should have stax.jar in your application's classpath. Download stax-1.2.0.jar from here:

Download stax-1.2.0.jar

Advantage of StAx parser

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

Streaming versus DOM

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.

When use Stax parser

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.

Dom, Sax and StAx parser comparision

Here is comparision chart of xml parsing apis:
Feature StAX SAX DOM
API Type Pull, streaming Push, streaming In memory tree
Ease of Use High Medium High
XPath Capability No No Yes
CPU and Memory Efficiency Good Good Varies
Forward Only Yes Yes No
Read XML Yes Yes Yes
Write XML Yes No Yes
Create, Read, Update, Delete No No Yes

Stax parser example

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 Source of is given below:

Here is Main class from where I am intiating stax parsing.


Share & Like

About is for Java, J2ee, Html5 and android developers. All tutorials are well explained and are easy to understand. We have tested every tutorials on our developement environment before posting it in public domain.