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















Core Software Performance Optimization Principles




Advertisements

High-Performance
Java Persistence
Close TOC

All Trails

Trail TOC

Page TOC

Previous

Next