Java Reference
In-Depth Information
How It Works
The Java standard library provides several ways to write XML documents. One model
is the Simple API for XML (SAX). The newer, simpler, and more efficient model is the
Streaming API for XML (StAX). This recipe uses StAX defined in the
javax.xml.stream
package. Writing an XML document takes five steps:
1.
Create a file output stream.
2.
Create an XML output factory and an XML output stream writer.
3.
Wrap the file stream in the XML stream writer.
4.
Use the XML stream writer's write methods to create the document
and write the XML elements.
5.
Close the output streams.
Create a file output stream using the
java.io.FileOutputStream
class. You
can use a
try-block
to open and close this stream. Learn more about the new
try-
block
syntax in
Chapter 9
.
The
javax.xml.stream.XMLOutputFactory
provides a static method that
creates an output factory. Use the factory to create a
javax.xml.stream.XMLStreamWriter
.
Once you have the writer, wrap the file stream object in the XML writer instance.
You will use the various write methods to create the XML document elements and at-
tributes. Finally, you simply close the writer when you finish writing to the file. Some
of the more useful methods of the
XMLStreamWriter
instance are these:
•
writeStartDocument()
•
writeStartElement()
•
writeEndElement()
•
writeEndDocument()
•
writeAttribute()
After creating the file and
XMLStreamWriter
, you always should begin the doc-
ument by calling the
writeStartDocumentMethod()
method. Follow this by
writing individual elements using the
writeStartElement()
and