I made a change in the blogger configuration to ease the later work when blogging. It is possible that older entries are not correctly formatted.

Monday, 7 January 2008

StAX- Streaming API for XML in Java

A number a way exist to access XML Data from Java. The DOM and SAX API are the two most traditional ones. A new alternatives under the form of the Streaming API for XML. This explanation uses the informations found in this tutorial.

The principle behing this API it to give the programmer the control over the next element of the file to be treated. This simplifies things greatly when there are many elements.

There are mainly two sets of APIs with the StaX API: cursor and iterator APIs.

Cursor API The cursor walks the documents one infoset element at a time and always forward. For this there are two interfaces: XMLStreamReader and XMLStreamWriter. These interfaces are very similar to the SAX handlers.

Iterator API

The Iterator API works on the idea, that the XML documents can be seen as a sequence of Events. Each of these Events are of a given type: StartDocument, StartElement, Attribute, ....

Differences. First of all, there are some things that are possible with the Iterator API which are not possible with the Cursor API. However, with the cursor API the code tends to be smaller and more efficient.

For processing events pipelines or modifiying the event stream use the iterator API.

In general, it is preferable to use the Iterator API, since this API is more easily extensible, thus it probably requires less refactoring for future versions of the applications.

Use of StaX APIs

The use of the StaX APIs is performed using the XMLInputFactory, XMLOutputFactory and XMLEventFactory classes. These factory classes are configured using the setProperty() method.