Implements a simple XML writer on top of java.io.PrintWriter. This implementation can be conveniently used to generate XML responses in servlets.
The XmlWriter class exposes a number of protected methods that enable it to be subclassed for the purposes of customizing its output. See {@link com.google.javascript.util.JsonWriter} for an example.
There are several behaviors of this class that are optionally available. These features are enabled by passing a {@code Set
}to the constructor: new XmlWriter(sw, EnumSet.of(WriterFlags.WRITE_HEADER, WriterFlags.EXPAND_EMPTY, WriterFlags.PRETTY_PRINT), null)
The caller can supply any of the values enumerated in {@link XmlWriter.WriterFlags}, or none. Once a feature has been enabled in the constructor, it cannot be turned off. Including XML Header
The {@code WRITE_HEADER} flags causes {@code XmlWriter} to emit an XMLheader at the beginning of the XML document: <?xml version='1.0'?>
Expanding Empty Elements
The {@code EXPAND_EMPTY} flags causes {@code XmlWriter} to emit "expanded"empty elements (elements consisting of distinct begin and end tags): <foo> <wee really="yeah"></wee> </foo>
Pretty Printing
The {@code PRETTY_PRINT} flag enables pretty printing. This featureformats the XML output with using new lines and tab characters:
<foo> <bar> <wee really="yeah"/> </bar> </foo>
Caveats
Elements containing mixed content (i.e. both text children and full-fledged elements) will not generally be formatted correctly. If your XML document contains mixed content, you may not want to use pretty printing: Will produce wonky formatting:
w.startElement(null, "txt", null, null); w.simpleElement(null, "fooey", null, null); w.characters("Kleenex"); w.endElement(null, "txt");
<txt> <fooey/>Kleenex </txt>
You can ensure correct formatting of mixed content in your document by using the {@link #innerXml(String)} method to write raw XML.
Correctly formatted:
w.startElement(null, "txt", null, null); w.innerXml("<fooey/>"); w.characters("Kleenex"); w.endElement(null, "txt");
<txt><fooey/>Kleenex</txt>