RSS Feed
Download our iPhone app
Browse DevX
Sign up for e-mail newsletters from DevX


StAX: DOM Ease with SAX Efficiency : Page 3

StAX (the Streaming API for XML) is a memory-efficient, simple, and convenient way to process XML while retaining control over the parsing and writing process.


StAX Output

No discussion of StAX is complete without mentioning StAX output. StAX is bi-directional in that it supports both read and write. The StAX XMLStreamWriter class provides a simple, low-level API to output XML data.

The following is an example of using StAX to generate an XML ATOM feed document:

File file = new File("atomoutput.xml");
FileOutputStream out = new FileOutputStream(file);
String now = new SimpleDateFormat().format(new Date(System.currentTimeMillis()));
XMLOutputFactory factory = XMLOutputFactory.newInstance();
XMLStreamWriter staxWriter = factory.createXMLStreamWriter(out);

staxWriter.writeStartDocument("UTF-8", "1.0");
// feed
staxWriter.writeNamespace("", "http://www.w3.org/2005/Atom");

// title
StaxUtil.writeElement(staxWriter,"title","Simple Atom Feed File");
// subtitle
StaxUtil.writeElement(staxWriter,"subtitle","Using StAX to read feed files");
// link
// updated
// author
// entry
staxWriter.writeEndElement(); // end feed

The resultant XML file is identical to the ATOM feed file previously shown in the "Patterns for Using StAX" section.

StAX Parsers

Several JSR-173-compliant parsers are available, including the following:
  1. Woodstox
  2. StAX Reference Implementation
  3. Oracle StAX Pull Parser
  4. BEA

You'll find the entire StAX JSR-173 on the JCP Web site.

Just How Fast Is StAX?

In addition to being easy to use, StAX is also very fast. Sun has released a whitepaper (PDF) that compares its performance with several other parsers.

The Future of StAX

StAX is ideally suited for no-nonsense, efficient XML input and output. The pull paradigm promotes a more intuitive parsing approach whereby application components can aggregate logically related parsing operations and pull what they want from the stream one element after another. Developers must still maintain appropriate state throughout the parsing process, but they retain overall control. StAX, like SAX, works well for large documents and when parts of the document can be dealt with in small chunks independently of other chunks. And best of all, it's fast.

Lara D'Abreo is an independent consultant with over 10 years experience in commercial product development in the US, Japan, and the UK. She's currently based out of Sydney, Australia and spends her time trying to make J2EE systems run faster.
Email AuthorEmail Author
Close Icon
Thanks for your registration, follow us on our social networks to keep up-to-date