Class XMLOutputter

  • All Implemented Interfaces:
    StatefulXMLEventListener, XMLEventListener, XMLEventListenerStates

    public class XMLOutputter
    extends java.lang.Object
    implements StatefulXMLEventListener
    Stream-based XML outputter. Instances of this class are able to write XML output to Writers.

    Standards compliance

    This class is intended to produce output that conforms to the XML 1.0 Specification. However, not all applicable restrictions are validated. For example, it is currently not checked if names contain characters that are invalid within a Name production.

    Furthermore, not all possible XML documents can be produced. The following limitations apply:

    • The name of the applicable encoding is always printed in the XML declaration, even though it may not be necessary.
    • The standalone attribute is not supported in the XML declaration.
    • Internal DTD subsets are not supported.
    • Spacing is fixed, whitespace is always kept to the minimum.

    Supported encodings

    The following encodings are supported:
    • UTF-8
    • UTF-16
    • ISO-10646-UCS-2
    • ISO-10646-UCS-4
    • ISO-10646-UTF-1
    • US-ASCII (also known as ASCII)
    • ISO-8859-n, where n is the part number

    Multi-threading

    This class is not thread-safe.

    Exceptions

    Note that all methods check the state first and then check the arguments. This means that if the state is incorrect and the arguments are incorrect, then an IllegalStateException will be thrown.

    If any of the writing methods generates an IOException, then the state will be set to XMLEventListenerStates.ERROR_STATE and no more output can be performed.

    Performance hints

    It is usually a good idea to let XMLOutputter instances write to buffered Writers. This typically improves performance on large documents or relatively slow or blocking output streams.

    Instances of this class can be cached in a pool to reduce object creations. Call reset() (with no arguments) when storing an instance in the pool. Use reset(Writer,String) (with 2 arguments) to re-initialize the instance after fetching it from the pool.

    Since:
    xmlenc 0.19
    Version:
    $Revision: 1.118 $ $Date: 2005/09/12 08:40:02 $
    Author:
    Ernst de Haan (wfe.dehaan@gmail.com), Jochen Schwoerer (j.schwoerer [at] web.de)
    • Constructor Summary

      Constructors 
      Constructor Description
      XMLOutputter()
      Constructs a new XMLOutputter.
      XMLOutputter​(java.io.Writer out, java.lang.String encoding)
      Constructs a new XMLOutputter for the specified Writer and encoding.
      XMLOutputter​(java.io.Writer out, XMLEncoder encoder)
      Constructs a new XMLOutputter for the specified Writer and encoder.
    • Method Summary

      All Methods Instance Methods Concrete Methods 
      Modifier and Type Method Description
      void attribute​(java.lang.String name, java.lang.String value)
      Adds an attribute to the current element.
      void cdata​(java.lang.String text)
      Writes a CDATA section.
      void close()
      Closes all open elements.
      void comment​(java.lang.String text)
      Writes the specified comment.
      void declaration()
      Writes the XML declaration.
      void dtd​(java.lang.String name, java.lang.String publicID, java.lang.String systemID)
      Writes a document type declaration.
      void endDocument()
      Ends the XML output.
      void endTag()
      Writes an element end tag.
      java.lang.String[] getElementStack()
      Returns a copy of the element stack.
      int getElementStackCapacity()
      Returns the current capacity for the stack of open elements.
      int getElementStackSize()
      Returns the current depth of open elements.
      java.lang.String getEncoding()
      Returns the encoding of this outputter.
      java.lang.String getIndentation()
      Returns the string currently used for indentation.
      LineBreak getLineBreak()
      Returns the currently used line break.
      char getQuotationMark()
      Gets the quotation mark character.
      XMLEventListenerState getState()
      Returns the current state of this outputter.
      java.io.Writer getWriter()
      Returns the output stream this outputter uses.
      boolean isEscaping()
      Checks if escaping is currently enabled.
      void pcdata​(char[] ch, int start, int length)
      Writes the specified character array as PCDATA.
      void pcdata​(java.lang.String text)
      Writes the specified String as PCDATA.
      void pi​(java.lang.String target, java.lang.String instruction)
      Writes a processing instruction.
      void reset()
      Resets this XMLOutputter.
      void reset​(java.io.Writer out, java.lang.String encoding)
      Resets this XMLOutputter and configures it for the specified output stream and encoding.
      void reset​(java.io.Writer out, XMLEncoder encoder)
      Resets this XMLOutputter and configures it for the specified output stream and encoder.
      void setElementStackCapacity​(int newCapacity)
      Sets the capacity for the stack of open elements.
      void setEscaping​(boolean escapeAmpersands)
      Sets if ampersands should be escaped.
      void setIndentation​(java.lang.String indentation)
      Sets the string to be used for indentation.
      void setLineBreak​(LineBreak lineBreak)
      Sets the type of line break to use.
      void setQuotationMark​(char c)
      Sets the quotation mark character to use.
      void setState​(XMLEventListenerState newState, java.lang.String[] newElementStack)
      Sets the state of this outputter.
      void startTag​(java.lang.String type)
      Writes an element start tag.
      void whitespace​(char[] ch, int start, int length)
      Writes text from the specified character array as ignorable whitespace.
      void whitespace​(java.lang.String whitespace)
      Writes the specified ignorable whitespace.
      • Methods inherited from class java.lang.Object

        clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
    • Field Detail

      • DEFAULT_INDENTATION

        public static final java.lang.String DEFAULT_INDENTATION
        Default indentation. This is the empty string, "", since by default no indentation is performed.
        See Also:
        Constant Field Values
    • Method Detail

      • getWriter

        public final java.io.Writer getWriter()
        Returns the output stream this outputter uses.
        Returns:
        the output stream of this encoding, only null if and only if the state is XMLEventListenerStates.UNINITIALIZED.
      • getEncoding

        public final java.lang.String getEncoding()
        Returns the encoding of this outputter.
        Returns:
        the encoding used by this outputter, only null if and only if the state is XMLEventListenerStates.UNINITIALIZED.
      • reset

        public final void reset​(java.io.Writer out,
                                java.lang.String encoding)
                         throws java.lang.IllegalArgumentException,
                                java.io.UnsupportedEncodingException
        Resets this XMLOutputter and configures it for the specified output stream and encoding. This resets the state to XMLEventListenerStates.BEFORE_XML_DECLARATION and clears the stack of open elements.
        Parameters:
        out - the output stream to write to, not null.
        encoding - the encoding, not null.
        Throws:
        java.lang.IllegalArgumentException - if out == null || encoding == null.
        java.io.UnsupportedEncodingException - if the specified encoding is not supported.
      • reset

        public final void reset​(java.io.Writer out,
                                XMLEncoder encoder)
                         throws java.lang.IllegalArgumentException,
                                java.io.UnsupportedEncodingException
        Resets this XMLOutputter and configures it for the specified output stream and encoder. This resets the state to XMLEventListenerStates.BEFORE_XML_DECLARATION and clears the stack of open elements.
        Parameters:
        out - the output stream to write to, not null.
        encoder - the encoder, not null.
        Throws:
        java.lang.IllegalArgumentException - if out == null || encoder == null.
        java.io.UnsupportedEncodingException - if the specified encoding is not supported.
      • isEscaping

        public final boolean isEscaping()
        Checks if escaping is currently enabled. If escaping is enabled, then all ampersand characters ('&') are replaced by the character entity reference "&". This affects PCDATA string printing (pcdata(String) and pcdata(char[],int,int)) and attribute value printing (attribute(String,String)).
        Returns:
        true if escaping is enabled, false otherwise.
      • setEscaping

        public final void setEscaping​(boolean escapeAmpersands)
        Sets if ampersands should be escaped. This affects PCDATA string printing (pcdata(String) and pcdata(char[],int,int)) and attribute value printing (attribute(String,String)).

        If ampersands are not escaped, then entity references can be printed.

        Parameters:
        escapeAmpersands - true if ampersands should be escaped, false otherwise.
        Since:
        xmlenc 0.24
      • getElementStack

        public final java.lang.String[] getElementStack()
        Returns a copy of the element stack. The returned array will be a new array. The size of the array will be equal to the element stack size (see getElementStackSize().
        Returns:
        a newly constructed array that contains all the element types currently on the element stack, or null if there are no elements on the stack.
        Since:
        xmlenc 0.22
      • getElementStackSize

        public final int getElementStackSize()
        Returns the current depth of open elements.
        Returns:
        the open element depth, always >= 0.
        Since:
        xmlenc 0.22
      • getElementStackCapacity

        public final int getElementStackCapacity()
        Returns the current capacity for the stack of open elements.
        Returns:
        the open element stack capacity, always >= getElementStackSize().
        Since:
        xmlenc 0.28
      • setElementStackCapacity

        public final void setElementStackCapacity​(int newCapacity)
                                           throws java.lang.IllegalArgumentException,
                                                  java.lang.OutOfMemoryError
        Sets the capacity for the stack of open elements. The new capacity must at least allow the stack to contain the current open elements.
        Parameters:
        newCapacity - the new capacity, >= getElementStackSize().
        Throws:
        java.lang.IllegalArgumentException - if newCapacity < getElementStackSize().
        java.lang.OutOfMemoryError - if a new array cannot be allocated; this object will still be usable, but the capacity will remain unchanged.
      • setQuotationMark

        public final void setQuotationMark​(char c)
                                    throws java.lang.IllegalArgumentException
        Sets the quotation mark character to use. This character is printed before and after an attribute value. It can be either the single or the double quote character.

        The default quotation mark character is '"'.

        Parameters:
        c - the character to put around attribute values, either '\'' or '"'.
        Throws:
        java.lang.IllegalArgumentException - if c != '\'' && c != '"'.
      • getQuotationMark

        public final char getQuotationMark()
        Gets the quotation mark character. This character is used to mark the start and end of an attribute value.

        The default quotation mark character is '"'.

        Returns:
        the character to put around attribute values, either '\'' or '"'.
      • setLineBreak

        public final void setLineBreak​(LineBreak lineBreak)
        Sets the type of line break to use. If the line break is set to LineBreak.NONE, then the indentation is reset to an empty string.
        Parameters:
        lineBreak - the line break to use; specifying null as the argument is equivalent to specifying LineBreak.NONE.
      • getLineBreak

        public final LineBreak getLineBreak()
        Returns the currently used line break.
        Returns:
        the currently used line break, never null.
      • setIndentation

        public final void setIndentation​(java.lang.String indentation)
                                  throws java.lang.IllegalStateException
        Sets the string to be used for indentation. A line break must be set prior to calling this method.

        Only space and tab characters are allowed for the indentation.

        Parameters:
        indentation - the character string used for indentation, or null if the default indentation should be used.
        Throws:
        java.lang.IllegalStateException - if getLineBreak() == LineBreak.NONE.
        java.lang.IllegalArgumentException - if indentation contains characters that are neither a space nor a tab.
      • getIndentation

        public final java.lang.String getIndentation()
        Returns the string currently used for indentation.
        Returns:
        the character string used for indentation, never null.
      • declaration

        public final void declaration()
                               throws java.lang.IllegalStateException,
                                      java.io.IOException
        Writes the XML declaration. This method always prints the name of the encoding. The case of the encoding is as it was specified during initialization (or re-initialization).

        If the encoding is set to "ISO-8859-1", then this method will produce the following output:

        <?xml version="1.0" encoding="ISO-8859-1"?>
        Specified by:
        declaration in interface XMLEventListener
        Throws:
        java.lang.IllegalStateException - if getState() != XMLEventListenerStates.BEFORE_XML_DECLARATION.
        java.io.IOException - if an I/O error occurs; this will set the state to XMLEventListenerStates.ERROR_STATE.
      • dtd

        public final void dtd​(java.lang.String name,
                              java.lang.String publicID,
                              java.lang.String systemID)
                       throws java.lang.IllegalStateException,
                              java.lang.IllegalArgumentException,
                              InvalidXMLException,
                              java.io.IOException
        Writes a document type declaration.

        An external subset can be specified using either a system identifier (alone), or using both a public identifier and a system identifier. It can never be specified using a public identifier alone.

        For example, for XHTML 1.0 the public identifier is:

        -//W3C//DTD XHTML 1.0 Transitional//EN

        while the system identifier is:

        http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd

        The output is typically similar to this:

        <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
        or alternatively, if only the system identifier is specified:
        <!DOCTYPE html SYSTEM "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
        Specified by:
        dtd in interface XMLEventListener
        Parameters:
        name - the name of the document type, not null.
        publicID - the public identifier, can be null, but if not, then it must match the PubidLiteral production in the XML 1.0 Specification, when quoted.
        systemID - the system identifier, can be null, but if not, then it must match the SystemLiteral production in the XML 1.0 Specification, when quoted.
        Throws:
        java.lang.IllegalStateException - if getState() != XMLEventListenerStates.BEFORE_XML_DECLARATION && getState() != XMLEventListenerStates.BEFORE_DTD_DECLARATION.
        java.lang.IllegalArgumentException - if name == null || (publicID != null && systemID == null).
        InvalidXMLException - if the specified name does not match the Name production (see XMLChecker.checkName(String)).
        java.io.IOException - if an I/O error occurs; this will set the state to XMLEventListenerStates.ERROR_STATE.
      • attribute

        public final void attribute​(java.lang.String name,
                                    java.lang.String value)
                             throws java.lang.IllegalStateException,
                                    java.lang.IllegalArgumentException,
                                    java.io.IOException
        Adds an attribute to the current element. There must currently be an open element.

        The attribute value is surrounded by single quotes.

        Specified by:
        attribute in interface XMLEventListener
        Parameters:
        name - the name of the attribute, not null.
        value - the value of the attribute, not null.
        Throws:
        java.lang.IllegalStateException - if getState() != XMLEventListenerStates.START_TAG_OPEN.
        java.lang.IllegalArgumentException - if name == null || value == null.
        java.io.IOException - if an I/O error occurs; this will set the state to XMLEventListenerStates.ERROR_STATE.
      • pcdata

        public final void pcdata​(char[] ch,
                                 int start,
                                 int length)
                          throws java.lang.IllegalStateException,
                                 java.lang.IllegalArgumentException,
                                 java.lang.IndexOutOfBoundsException,
                                 InvalidXMLException,
                                 java.io.IOException
        Writes the specified character array as PCDATA.
        Specified by:
        pcdata in interface XMLEventListener
        Parameters:
        ch - the character array containing the text to be written, not null.
        start - the start index in the array, must be >= 0 and it must be < ch.length.
        length - the number of characters to read from the array, must be > 0.
        Throws:
        java.lang.IllegalStateException - if getState() != XMLEventListenerStates.START_TAG_OPEN && getState() != XMLEventListenerStates.WITHIN_ELEMENT
        java.lang.IllegalArgumentException - if ch == null || start < 0 || start >= ch.length || length < 0.
        java.lang.IndexOutOfBoundsException - if start + length > ch.length.
        InvalidXMLException - if the specified text contains an invalid character.
        java.io.IOException - if an I/O error occurs; this will set the state to XMLEventListenerStates.ERROR_STATE.
      • cdata

        public final void cdata​(java.lang.String text)
                         throws java.lang.IllegalStateException,
                                java.lang.IllegalArgumentException,
                                java.io.IOException
        Writes a CDATA section.

        A CDATA section can contain any string, except "]]>". This will, however, not be checked by this method.

        Left angle brackets and ampersands will be output in their literal form; they need not (and cannot) be escaped using "&lt;" and "&amp;".

        If the specified string is empty (i.e. "".equals(text), then nothing will be output.

        If the specified string contains characters that cannot be printed in this encoding, then the result is undefined.

        Specified by:
        cdata in interface XMLEventListener
        Parameters:
        text - the contents of the CDATA section, not null.
        Throws:
        java.lang.IllegalStateException - if getState() != XMLEventListenerStates.START_TAG_OPEN && getState() != XMLEventListenerStates.WITHIN_ELEMENT
        java.lang.IllegalArgumentException - if text == null.
        java.io.IOException - if an I/O error occurs; this will set the state to XMLEventListenerStates.ERROR_STATE.