background image

Writing XML Streams

<< Reading Attributes | Using XMLEventWriter >>
<< Reading Attributes | Using XMLEventWriter >>
W
RITING
XML S
TREAMS
95
the current namespace context by using
StartElement.getNamespaceCon-
text()
.
Writing XML Streams
StAX is a bidirectional API, and both the cursor and event iterator APIs have
their own set of interfaces for writing XML streams. As with the interfaces for
reading streams, there are significant differences between the writer APIs for
cursor and event iterator. The following sections describe how to write XML
streams using each of these APIs.
Using XMLStreamWriter
The
XMLStreamWriter
interface in the StAX cursor API lets applications write
back to an XML stream or create entirely new streams. XMLStreamWriter has
methods that let you:
· Write well-formed XML
· Flush or close the output
· Write qualified names
Note that
XMLStreamWriter
implementations are not required to perform well-
formedness or validity checks on input. While some implementations my per-
form strict error checking, others may not. The rules you choose to implement
are set on properties provided by the
XMLOutputFactory
class.
The
writeCharacters(...)
method is used to escape characters such as
&
,
<
,
>
,
and
"
. Binding prefixes can be handled by either passing the actual value for the
prefix, by using the
setPrefix()
method, or by setting the property for default-
ing namespace declarations.
The following example, taken from the StAX specification, shows how to instan-
tiate an output factory, create a writer and write XML output:
XMLOutputFactory output = XMLOutputFactory.newInstance();
XMLStreamWriter writer = output.createXMLStreamWriter( ... );
writer.writeStartDocument();
writer.setPrefix("c","http://c");
writer.setDefaultNamespace("http://c");
writer.writeStartElement("http://c","a");
writer.writeAttribute("b","blah");
writer.writeNamespace("c","http://c");
writer.writeDefaultNamespace("http://c");