Tech and Media Labs
This site uses cookies to improve the user experience.

Java StAX: XMLEventWriter - The Iterator Writer API

Jakob Jenkov
Last update: 2014-05-21

The XMLEventWriter class in the Java StAX API allows you to write StAX XMLEvent's either to a Writer, an OutputStream, or a Result (special JAXP object).

Here is a simple example that writes a series of events to disk, using a FileWriter:

XMLOutputFactory factory      = XMLOutputFactory.newInstance();
XMLEventFactory  eventFactory = XMLEventFactory.newInstance();

try {
    XMLEventWriter writer =
                    new FileWriter("data\\output.xml"));

    XMLEvent event = eventFactory.createStartDocument();

    event = eventFactory.createStartElement(
            "jenkov", "", "document");

    event = eventFactory.createNamespace(
            "jenkov", "");

    event = eventFactory.createAttribute
            ("attribute", "value");

    event = eventFactory.createEndElement(
            "jenkov", "", "document");

} catch (XMLStreamException e) {
} catch (IOException e) {

The result of executing this code is the following XML file (line breaks inserted for readability):

<?xml version='1.0' encoding='UTF-8'?>
<jenkov:document xmlns:jenkov="" attribute="value">

As you can see, it is possible to generate XML using XMLEvent's and the XMLEventWriter. But, if you are looking to just output some quick XML, you might be better off using the XMLStreamWriter instead. It's API is easier to work with, and results in more dense code.

Chaining XMLEventReader and XMLEventWriter

It is possible to add the XMLEvent's available from an XMLEventReader directly to an XMLEventWriter. In other words, you are pooring the XML events from the reader directly into the writer. You do so using the XMLEventWriter.add(XMLEventReader) method.

Jakob Jenkov

Copyright  Jenkov Aps
Close TOC