background image

Writing XML Streams

<< Using XMLEventReader | Using XMLEventWriter >>
<< Using XMLEventReader | Using XMLEventWriter >>

Writing XML Streams

Reading Namespaces
Similar to reading attributes, namespaces are read using an Iterator created by calling the
getNamespaces
method on the StartElement interface. Only the namespace for the current
StartElement
is returned, and an application can get the current namespace context by using
StartElement.getNamespaceContext
.
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 may perform strict error checking,
others may not. The rules you implement are applied to properties defined in 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 defaulting namespace declarations.
The following example, taken from the StAX specification, shows how to instantiate 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");
writer.setPrefix(
"d","http://c");
writer.writeEmptyElement(
"http://c","d");
Using StAX
The Java EE 5 Tutorial · September 2007
564