April 19, 2014
Hot Topics:
RSS RSS feed Download our iPhone app

Delving Deeper Into StAX

  • June 22, 2004
  • By Jeff Ryan
  • Send Email »
  • More Articles »

Introduction

In my previous article, Does StAX Stack Up?, I introduced StAX (Streaming API for XML), the new parsing API in the JAXP (Java API for XML Processing) family. We talked about how StAX fit in with its sister API, downloaded the reference implementation, and developed some simple examples of using the StAX cursor based API for reading and writing documents. In this article, we'll dive deeper into StAX and introduce the features of the more advanced event iterator API.

StAX API Overview

While StAX is an option to consider versus DOM (Document Object Model), SAX (Simple API for XML) and TrAX (Transformation API for XML), within StAX itself, there are options to consider. StAX has both a cursor API and an event iterator API. Each of these APIs has a reading and writing side. This is depicted in the following diagram:

Cursor API Recap

In the previous article, we built the equivalent of "Hello world!" examples using the read and write sides of the cursor API. Conceptually, the cursor-based API moves a virtual cursor over the XML document.

On the reading side, an instance of an XMLStreamReader is obtained from the XMLInputFactory. The iterator API exposes hasNext() and next() methods that are used to read through the document in a forward only manner. Accessor methods such as getText() are used to read the current event which may be an element, attribute, or data. Interrogator methods such as isStartElement() help parse elements, attributes, and data from the document. Here is a sample code snippet for reference:

XMLInputFactory factory = XMLInputFactory.newInstance();

XMLStreamReader reader =
   factory.createXMLStreamReader(new FileReader("test.xml"));

while (reader.hasNext())
{
   if (reader.isStartElement())
   {
      System.out.print(reader.getText());
   }
   reader.next();
}
reader.close();

On the writing side of the API, an interface is exposed to write elements, attributes, and data. An instance of an XMLStreamWriter is obtained from the XMLOutputFactory. Once again, a simple example is provided for reference:

XMLOutputFactory.newInstance();

XMLStreamWriter writer =
   factory.createXMLStreamWriter(new FileWriter("test.xml"));

writer.writeStartDocument();
writer.writeStartElement("Name");
writer.writeCharacters("Jeff");
writer.writeEndElement("Name");
writer.writeEndDocument();
writer.flush();




Page 1 of 4



Comment and Contribute

 


(Maximum characters: 1200). You have characters left.

 

 


Sitemap | Contact Us

Rocket Fuel