Java API for XML (JAXP) – StAX

StAX API in JAXP

StAX stands for Streaming API for XML. In the earlier tutorials we have seen DOM (Document Object Model) where a Document tree is created out of the xml and the entire document tree is stored in memory. We have also see the SAX (Simple API for XML) API wherein the parser fires events for different components of the XML and the events need to be handled by the client. Each method of parsing has its pros and cons. In this tutorial we look at the third way of parsing an xml document – StAX. The StAX API makes the XML document available as a stream of events. However, unlike SAX, the client asks for the next event from the parser. The history or state of the XML Document is not maintained and hence the client code needs to store the state in its context. There are two kinds of StAX API :

  • Stream based – The Stream based API considers the XML Document as a stream of XML events. The cursor points to the current event in the XML document. The client can move the cursor forward and retrive the element that the cursor is currently pointing to.
  • Event based – The Event based API presents the XML as a sequence of XMLEvents that the user can request for. The API provides a method called peek that enables the user to peek at the type of next element without actually requesting for the next event.

JAXP provider readers and writers for both the stream API and the reader API. In the examples below we will look at how to read an XML document using the stream and reader API and how to write an XML document using a reader API.

Examples

In the first example we look at parsing an XML document using an event based API.

In the second example we look at parsing an XML document using a stream based parser

Last we look at ways to write to an XML document. In this example we read the bbc xml and rewrite it to a modified xml after changing the title.(we add the word studytrail at the beginning of the title)

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Scroll to top
Bitnami