background image

Creating the Output Factory

<< Creating a Writer | Running readnwrite Sample >>
<< Creating a Writer | Running readnwrite Sample >>
114
S
TREAMING
API
FOR
XML
<Publisher>Harper &amp; Row</Publisher>
<Cost currency="USD">2.95</Cost>
</Book>
</BookCatalogue>
writer Sample ­ CursorWriter.java
Located in the
<javaee.tutorial.home>/examples/stax/writer
directory,
CursorWriter.java
demonstrates how to use the StAX cursor API to write an
XML stream.
Creating the Output Factory
The first step is to create an instance of
XMLOutputFactory
:
XMLOutputFactory xof = XMLOutputFactory.newInstance();
Creating a Stream Writer
The next step is to create an instance of
XMLStreamWriter
:
XMLStreamWriter xtw = null;
Writing the Stream
The final step is to write the XML stream. Note that the stream is flushed and
closed after the final
EndDocument
is written:
xtw = xof.createXMLStreamWriter(new FileWriter(fileName));
xtw.writeComment("all elements here are explicitly in the HTML
namespace");
xtw.writeStartDocument("utf-8","1.0");
xtw.setPrefix("html", "http://www.w3.org/TR/REC-html40");
xtw.writeStartElement("http://www.w3.org/TR/REC-
html40","html");
xtw.writeNamespace("html", "http://www.w3.org/TR/REC-html40");
xtw.writeStartElement("http://www.w3.org/TR/REC-
html40","head");
xtw.writeStartElement("http://www.w3.org/TR/REC-
html40","title");
xtw.writeCharacters("Frobnostication");
xtw.writeEndElement();