2.7.5. Writing an XML Document with StAX

In the preceding section, you saw how to produce an XML document by writing a DOM tree. If you have no other use for the DOM tree, that approach is not very efficient.

The StAX API lets you write an XML tree directly. Construct an XMLStreamWriter from an OutputStream:

XMLOutputFactory factory = XMLOutputFactory.newInstance(); XMLStreamWriter writer = factory.createXMLStreamWriter(out);

To produce the XML header, call


Then call


Add attributes by calling

writer.writeAttribute(name, value);

Now you can add child elements by calling writeStartElement again, or write characters with


When you ...

Get Core Java® Volume II—Advanced Features, Ninth Edition now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.