Java StAX: XMLStreamWriter - The Cursor Writer API

Jakob Jenkov
Last update: 2014-05-21

The XMLStreamWriter class in the Java StAX API allows you to write XML events (elements, attributes etc.) 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();

 try {
     XMLStreamWriter writer = factory.createXMLStreamWriter(
             new FileWriter("data\\output2.xml"));

     writer.writeStartDocument();
     writer.writeStartElement("document");
     writer.writeStartElement("data");
     writer.writeAttribute("name", "value");
     writer.writeEndElement();
     writer.writeEndElement();
     writer.writeEndDocument();

     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'?>
<document><data name="value"></data></document>

Jakob Jenkov

Featured Videos

Java Generics

Java ForkJoinPool

P2P Networks Introduction



















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