background image

Using XMLEventWriter

<< Writing XML Streams | Streaming XML Parser Implementation >>
<< Writing XML Streams | Streaming XML Parser Implementation >>

Using XMLEventWriter

writer.writeAttribute(
"http://c","chris","fry");
writer.writeNamespace(
"d","http://c");
writer.writeCharacters(
"Jean Arp");
writer.writeEndElement();
writer.flush();
This code generates the following XML (new lines are non-normative):
<?xml version=
'1.0' encoding='utf-8'?>
<a b=
"blah" xmlns:c="http://c" xmlns="http://c">
<d:d d:chris=
"fry" xmlns:d="http://c"/>Jean Arp</a>
Using XMLEventWriter
The XMLEventWriter interface in the StAX event iterator API lets applications write back to an
XML stream or create entirely new streams. This API can be extended, but the main API is as
follows:
public interface XMLEventWriter {
public void flush() throws XMLStreamException;
public void close() throws XMLStreamException;
public void add(XMLEvent e) throws XMLStreamException;
// ... other methods not shown.
}
Instances of XMLEventWriter are created by an instance of XMLOutputFactory. Stream events
are added iteratively, and an event cannot be modified after it has been added to an event writer
instance.
Attributes, Escaping Characters, Binding Prefixes
StAX implementations are required to buffer the last StartElement until an event other than
Attribute
or Namespace is added or encountered in the stream. This means that when you add
an Attribute or a Namespace to a stream, it is appended the current StartElement event.
You can use the Characters method to escape characters like &, <, >, and ".
The setPrefix(...) method can be used to explicitly bind a prefix for use during output, and
the getPrefix(...) method can be used to get the current prefix. Note that by default,
XMLEventWriter
adds namespace bindings to its internal namespace map. Prefixes go out of
scope after the corresponding EndElement for the event in which they are bound.
Using StAX
Chapter 18 · Streaming API for XML
565