com.google.gdata.util.common.xml
Class XmlWriter

java.lang.Object
  extended by com.google.gdata.util.common.xml.XmlWriter

public class XmlWriter
extends java.lang.Object

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 com.google.javascript.util.JsonWriter for an example.

Optional Behaviors

There are several behaviors of this class that are optionally available. These features are enabled by passing a Set<XmlWriter.WriterFlags> 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 XmlWriter.WriterFlags, or none. Once a feature has been enabled in the constructor, it cannot be turned off.

Including XML Header

The WRITE_HEADER flags causes XmlWriter to emit an XML header at the beginning of the XML document:
<?xml version='1.0'?>

Expanding Empty Elements

The EXPAND_EMPTY flags causes XmlWriter to emit "expanded" empty elements (elements consisting of distinct begin and end tags):
 <foo>
    <wee really="yeah"></wee>
 </foo>

Pretty Printing

The PRETTY_PRINT flag enables pretty printing. This feature formats 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 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>


Nested Class Summary
static class XmlWriter.Attribute
          The Attribute class represents an XML attribute.
protected static class XmlWriter.Element
          The Element class contains information about an XML element.
static class XmlWriter.Namespace
          Deprecated. Use the XmlNamespace class instead.
static class XmlWriter.WriterFlags
          Enumeration type that can be used to configure the XmlWriter behavior.
 
Field Summary
protected  java.lang.String encoding
          Encoding of output
protected  java.util.Set<XmlWriter.WriterFlags> flags
           
protected  java.io.Writer writer
          The underlying output Writer associated with this XmlWriter.
 
Constructor Summary
XmlWriter(java.io.Writer w)
          Constructs an XmlWriter instance associated that will generate XML content to an underlying Writer.
XmlWriter(java.io.Writer w, boolean includeHeader)
          Deprecated. see XmlWriter(Writer, Set, String)
XmlWriter(java.io.Writer w, java.util.Set<XmlWriter.WriterFlags> f, java.lang.String encoding)
          The default namespace that will take effect on the next element transition.
XmlWriter(java.io.Writer w, java.util.Set<XmlWriter.WriterFlags> f, java.lang.String encoding, boolean standalone)
          Constructor that allows standalone directive to be provided.
XmlWriter(java.io.Writer w, java.lang.String encoding)
          Constructor that writers header including encoding information.
 
Method Summary
 void characters(java.lang.String s)
          Emits character data subject to XML escaping.
 void characters(java.lang.String s, boolean useCData)
          Emits character data subject to either XML escaping or CDATA escaping.
 void close()
          Closes the XmlWriter and the underlying output writer.
protected  XmlWriter.Element createElement(java.lang.String nsAlias, java.lang.String nsUri, java.lang.String name)
          Constructs an Element instance that describes an XML element that is about to be written.
protected  XmlWriter.Element currentElement()
          Returns the current element, or null if no element is being written.
 void endElement()
          Ends the current element.
 void endElement(XmlNamespace namespace, java.lang.String name)
          Ends the current element.
protected  void endOpenTag()
          Ends the start tag for an element.
 void endRepeatingElement()
          Indicates that the series of repeating elements have been completely written.
protected  java.lang.String ensureNamespace(XmlNamespace namespace)
          Ensures the namespace is in scope and returns its alias.
 void flush()
          Flushes the XmlWriter and the underlying output writer.
protected  java.lang.String getNamespaceUri(java.lang.String nsAlias)
          Returns the namespace URI associated with a given namespace alias.
 void innerXml(java.lang.String xml)
          Writes inner XML provided as a string.
protected  XmlWriter.Element parentElement()
          Return parent of current element.
 void setDefaultNamespace(XmlNamespace namespace)
          Sets the default namespace.
protected  boolean shouldWriteHeaderAndFooter()
          Tests whether header and footer should be included in output
 void simpleElement(java.lang.String name, java.lang.String value)
          Emits a simple element (without child elements).
 void simpleElement(XmlNamespace namespace, java.lang.String name, java.util.List<XmlWriter.Attribute> attrs, java.lang.String value)
          Emits a simple element (without child elements).
 void startElement(java.lang.String name)
          Starts an element.
 void startElement(XmlNamespace namespace, java.lang.String name, java.util.Collection<XmlWriter.Attribute> attrs, java.util.Collection<? extends XmlNamespace> namespaceDecls)
          Starts an element.
 void startRepeatingElement()
          Indicates that a series of repeating elements are about to be written.
protected  void writeAttribute(java.lang.String name, java.lang.String value)
          Writes an unqualfied XML attribute.
protected  void writeAttribute(java.lang.String nsAlias, java.lang.String name, java.lang.String value)
          Writes a namespace-qualified XML attribute.
protected  void writeBeginOutput()
          writes beginning of output if any.
protected  void writeCloseTag(java.lang.String nsAlias, java.lang.String name)
          Writes the closing tag of an element, after all nested elements and value text have been written.
protected  void writeEndOutput()
          Writes any closing information to the output writer.
protected  void writeFooter()
          Writes footer, if any, that corresponds to the header.
protected  void writeHeader(java.lang.String enc)
          Writes basic XML headers including XML version, standalone, and encoding.
protected  void writeOpenTagEnd()
          Writes the end of the opening tag of an element after all attributes have been written.
protected  void writeOpenTagStart(java.lang.String nsAlias, java.lang.String name)
          Writes the start of the opening tag of an element.
protected  void writeQualifiedName(java.lang.String nsAlias, java.lang.String name)
          Writes a namespace qualified element or attribute name.
 void writeUnescaped(java.lang.String s)
          Writes a string without XML entity escaping.
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
 

Field Detail

flags

protected final java.util.Set<XmlWriter.WriterFlags> flags

writer

protected final java.io.Writer writer
The underlying output Writer associated with this XmlWriter.


encoding

protected java.lang.String encoding
Encoding of output

Constructor Detail

XmlWriter

public XmlWriter(java.io.Writer w,
                 java.util.Set<XmlWriter.WriterFlags> f,
                 java.lang.String encoding,
                 boolean standalone)
          throws java.io.IOException
Constructor that allows standalone directive to be provided. Please note that using this constructor explicity causes the standalone header value to be written and WRITE_HEADER flag to be set.

Parameters:
w - output writer object.
f - writer configuration flags or null for no flags
encoding - charset encoding.
standalone - boolean where true=yes and false=no.
Throws:
java.io.IOException - thrown by the underlying writer
See Also:
XmlWriter.WriterFlags

XmlWriter

public XmlWriter(java.io.Writer w,
                 java.util.Set<XmlWriter.WriterFlags> f,
                 java.lang.String encoding)
          throws java.io.IOException
The default namespace that will take effect on the next element transition.

Parameters:
w - output writer object.
f - writer configuration flags or null for no flags
encoding - charset encoding. When non-null, implicitly causes the WRITE_HEADER flag to be set.
Throws:
java.io.IOException - thrown by the underlying writer.
See Also:
XmlWriter.WriterFlags

XmlWriter

public XmlWriter(java.io.Writer w)
          throws java.io.IOException
Constructs an XmlWriter instance associated that will generate XML content to an underlying Writer.

Parameters:
w - output writer object.
Throws:
java.io.IOException - thrown by the underlying writer.

XmlWriter

public XmlWriter(java.io.Writer w,
                 java.lang.String encoding)
          throws java.io.IOException
Constructor that writers header including encoding information.

Parameters:
w - Output writer object.
encoding - output encoding to use in declaration.
Throws:
java.io.IOException - thrown by the underlying writer.

XmlWriter

@Deprecated
public XmlWriter(java.io.Writer w,
                            boolean includeHeader)
          throws java.io.IOException
Deprecated. see XmlWriter(Writer, Set, String)

Throws:
java.io.IOException
Method Detail

close

public void close()
           throws java.io.IOException
Closes the XmlWriter and the underlying output writer.

Throws:
java.io.IOException - thrown by the underlying writer.

flush

public void flush()
           throws java.io.IOException
Flushes the XmlWriter and the underlying output writer.

Throws:
java.io.IOException - thrown by the underlying writer.

setDefaultNamespace

public void setDefaultNamespace(XmlNamespace namespace)
Sets the default namespace. It takes effect on the next element.

Parameters:
namespace - the new namespace to set as the default at the start of the next element.

createElement

protected XmlWriter.Element createElement(java.lang.String nsAlias,
                                          java.lang.String nsUri,
                                          java.lang.String name)
Constructs an Element instance that describes an XML element that is about to be written.


currentElement

protected XmlWriter.Element currentElement()
Returns the current element, or null if no element is being written.


parentElement

protected XmlWriter.Element parentElement()
Return parent of current element. Stack has a dummy root element so every real element has non-null a parent.

Returns:
Parent element.

startElement

public void startElement(java.lang.String name)
                  throws java.io.IOException
Starts an element. This element can be a parent to other elements.

Parameters:
name - element name.
Throws:
java.io.IOException

startElement

public void startElement(XmlNamespace namespace,
                         java.lang.String name,
                         java.util.Collection<XmlWriter.Attribute> attrs,
                         java.util.Collection<? extends XmlNamespace> namespaceDecls)
                  throws java.io.IOException
Starts an element. This element can be a parent to other elements.

Parameters:
namespace - element namespace.
name - element name.
attrs - attributes. Can be null.
namespaceDecls - extra namespace declarations. Can be null.
Throws:
java.io.IOException - thrown by the underlying writer.

shouldWriteHeaderAndFooter

protected boolean shouldWriteHeaderAndFooter()
Tests whether header and footer should be included in output

Returns:
true if header and footer should be included in output; false otherwise

endOpenTag

protected void endOpenTag()
                   throws java.io.IOException
Ends the start tag for an element.

Throws:
java.io.IOException

endElement

public void endElement(XmlNamespace namespace,
                       java.lang.String name)
                throws java.io.IOException
Ends the current element. It is expected to be on top of the stack.

Parameters:
namespace - element namespace.
name - element name.
Throws:
java.io.IOException

endElement

public void endElement()
                throws java.io.IOException
Ends the current element. No integrity checking is performed.

Throws:
java.io.IOException

simpleElement

public void simpleElement(java.lang.String name,
                          java.lang.String value)
                   throws java.io.IOException
Emits a simple element (without child elements).

Parameters:
name - element name.
value - element value. Can be null.
Throws:
java.io.IOException - thrown by the underlying writer.

startRepeatingElement

public void startRepeatingElement()
                           throws java.io.IOException
Indicates that a series of repeating elements are about to be written.

Throws:
java.io.IOException

endRepeatingElement

public void endRepeatingElement()
                         throws java.io.IOException
Indicates that the series of repeating elements have been completely written.

Throws:
java.io.IOException

simpleElement

public void simpleElement(XmlNamespace namespace,
                          java.lang.String name,
                          java.util.List<XmlWriter.Attribute> attrs,
                          java.lang.String value)
                   throws java.io.IOException
Emits a simple element (without child elements).

Parameters:
namespace - element namespace.
name - element name.
attrs - attributes. Can be null.
value - element value. Can be null.
Throws:
java.io.IOException - thrown by the underlying writer.

ensureNamespace

protected java.lang.String ensureNamespace(XmlNamespace namespace)
Ensures the namespace is in scope and returns its alias. The top of the stack is assumed to be the current element. If the namespace is not found, it is appended to the current element.

Returns:
namespace alias or null for the default namespace.

getNamespaceUri

protected java.lang.String getNamespaceUri(java.lang.String nsAlias)
Returns the namespace URI associated with a given namespace alias.

Parameters:
nsAlias - namespace alias, or null for default namespace.
Returns:
namespace URI, or null if not found.

writeBeginOutput

protected void writeBeginOutput()
                         throws java.io.IOException
writes beginning of output if any.

Throws:
java.io.IOException

writeEndOutput

protected void writeEndOutput()
                       throws java.io.IOException
Writes any closing information to the output writer. This is used by subclasses to write anything they need to close out the object. close() should not be used because it closes the underlying stream, which we don't always want to do.

Throws:
java.io.IOException

writeHeader

protected void writeHeader(java.lang.String enc)
                    throws java.io.IOException
Writes basic XML headers including XML version, standalone, and encoding.

Parameters:
enc - the XML encoding for the output. Can be null.
Throws:
java.io.IOException - thrown by the underlying writer.

writeFooter

protected void writeFooter()
                    throws java.io.IOException
Writes footer, if any, that corresponds to the header.

Throws:
java.io.IOException

writeQualifiedName

protected void writeQualifiedName(java.lang.String nsAlias,
                                  java.lang.String name)
                           throws java.io.IOException
Writes a namespace qualified element or attribute name.

Parameters:
nsAlias - namespace alias prefix.
name - namespace-relative local name.
Throws:
java.io.IOException - thrown by the underlying writer.

writeOpenTagStart

protected void writeOpenTagStart(java.lang.String nsAlias,
                                 java.lang.String name)
                          throws java.io.IOException
Writes the start of the opening tag of an element.

Parameters:
nsAlias - namespace alias prefix for the element.
name - tag name for the element.
Throws:
java.io.IOException - thrown by the underlying writer.

writeOpenTagEnd

protected void writeOpenTagEnd()
                        throws java.io.IOException
Writes the end of the opening tag of an element after all attributes have been written.

Throws:
java.io.IOException - thrown by the underlying writer.

writeCloseTag

protected void writeCloseTag(java.lang.String nsAlias,
                             java.lang.String name)
                      throws java.io.IOException
Writes the closing tag of an element, after all nested elements and value text have been written.

Parameters:
nsAlias - namespace alias prefix for the element.
name - tag name for the element.
Throws:
java.io.IOException - thrown by the underlying writer.

writeAttribute

protected void writeAttribute(java.lang.String name,
                              java.lang.String value)
                       throws java.io.IOException
Writes an unqualfied XML attribute.

Parameters:
name - the name of the attribute.
value - the value of the attribute.
Throws:
java.io.IOException - thrown by the underlying writer.

writeAttribute

protected void writeAttribute(java.lang.String nsAlias,
                              java.lang.String name,
                              java.lang.String value)
                       throws java.io.IOException
Writes a namespace-qualified XML attribute.

Parameters:
nsAlias - namespace alias prefix for the attribute.
name - the name of the attribute.
value - the value of the attribute.
Throws:
java.io.IOException - thrown by the underlying writer.

characters

public void characters(java.lang.String s)
                throws java.io.IOException
Emits character data subject to XML escaping.

Parameters:
s - string to emit. Can be null.
Throws:
java.io.IOException - thrown by the underlying writer.

characters

public void characters(java.lang.String s,
                       boolean useCData)
                throws java.io.IOException
Emits character data subject to either XML escaping or CDATA escaping.

Parameters:
s - string to emit. Can be null.
useCData - CDATA used if true, XML escaping if false
Throws:
java.io.IOException - thrown by the underlying writer.

innerXml

public void innerXml(java.lang.String xml)
              throws java.io.IOException
Writes inner XML provided as a string. Used to write out XML blobs.

Parameters:
xml - XML blob string.
Throws:
java.io.IOException - thrown by the underlying writer.

writeUnescaped

public void writeUnescaped(java.lang.String s)
                    throws java.io.IOException
Writes a string without XML entity escaping.

Parameters:
s - the raw content to write without escaping.
Throws:
java.io.IOException - thrown by the underlying writer.