Java StAX: XMLEventWriter - The Iterator Writer API

Jakob Jenkov
Last update: 2024-03-29

The Java XMLEventWriter class in the Java StAX API allows you to write StAX XMLEvent's either to an instance of 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 =
            factory.createXMLEventWriter(
                    new FileWriter("data\\output.xml"));

    XMLEvent event = eventFactory.createStartDocument();
    writer.add(event);

    event = eventFactory.createStartElement(
            "jenkov", "http://jenkov.com", "document");
    writer.add(event);

    event = eventFactory.createNamespace(
            "jenkov", "http://jenkov.com");
    writer.add(event);

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

    event = eventFactory.createEndElement(
            "jenkov", "http://jenkov.com", "document");
    writer.add(event);

    writer.flush();
    writer.close();
} catch (XMLStreamException e) {
    e.printStackTrace();
} catch (IOException e) {
    e.printStackTrace();
}

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="http://jenkov.com" attribute="value">
</jenkov:document>

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

Featured Videos

Java ForkJoinPool

P2P Networks Introduction




















Advertisements

High-Performance
Java Persistence
Close TOC
All Tutorial Trails
All Trails
Table of contents (TOC) for this tutorial trail
Trail TOC
Table of contents (TOC) for this tutorial
Page TOC
Previous tutorial in this tutorial trail
Previous
Next tutorial in this tutorial trail
Next