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);
StaxUtil.writeElement(staxWriter,"title","Simple Atom Feed File");
StaxUtil.writeElement(staxWriter,"subtitle","Using StAX to read feed files");
staxWriter.writeEndElement(); // end feed
The resultant XML file is identical to the ATOM feed file previously shown in the "Patterns for Using StAX" section.
Several JSR-173-compliant parsers are available, including the following:
- StAX Reference Implementation
- Oracle StAX Pull Parser
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.