java.lang.Object
com.aquima.interactions.foundation.xml.generation.XmlGenerator
All Implemented Interfaces:
Serializable

public class XmlGenerator extends Object implements Serializable
DOM Generator to create simple XML documents on the fly.

Quick usage overview:

  1. beginDocument
  2. ... create child nodes ...
  3. addChild..... repeat. Nest to create hierarchies
  4. endDocument
  5. toXML / writeXML

Using beginDocumentFragment instead of beginDocument it is also possible to create a document fragment instead of a full XML document. A document fragment has no header or doctype declaration, a full document does have these.

Notice that the way the document is constructed is usually inside-out, that is, the child elements have to be created first and added to their parent, before the parent is added etc. This is not required when using the special method that adds references, not copies, of the elements. But beware of the implications of that method!

Properly escapes unallowed characters such as ", &, <, >, '. But pay attention to the escaping method!! See 'escape' !!!

Some simple consistency checks are done, so that this generator always outputs 100% valid XML syntax.

Only simple XML docs can be constructed, with tags and attributes and XML comments. Character encoding types such as UTF-16, UNICODE are fully supported, as long as the Java runtime knows about them. Except for Entity Declarations, other declarations, processing instructions etc. are NOT supported!! Maybe a future version will be more sophisticated.

This class is not synchronized/thread safe by itself please bear in mind the escaping method used for special XML characters, see the escape method.

Since:
5.0
Author:
IdJ
See Also:
  • Constructor Summary

    Constructors
    Constructor
    Description
    Constructs a new empty generator.
    shortcut constructor, to perform the most used steps in one go: creates an XMLGenerator calls beginDocument adds the given element as root node calls endDocument Usually you'll create the XML structure using XMLNewElement objects, and then create an XMLGenerator to write the XML source.
  • Method Summary

    Modifier and Type
    Method
    Description
    void
    add this document as a document fragment to another parent element.
    void
    Adds a new element to the XML document.
    void
    addChild(XmlGenerator docFragment)
    Adds a document fragment to another document.
    void
    Begins a new XML document.
    void
    Begins a new XML document with given encoding type.
    void
    Begins a new XML document fragment (a part of a full document, without header).
    void
    beginDocumentFragment(int indentLevel)
    Begin a new XML document fragment (a part of a full document, without header).
    void
    Clear everything, the generator can now be reused for a new document.
    void
    Ends the XML document, it is now finished and can be converted to an XML string for instance.
    protected static void
    escape(String str, StringBuffer outputBuffer)
    internal escape method operating on a StringBuffer.
    Returns the current default namespace uri.
    returns the current character encoding that will be used for XML generation.
    Returns the current table of namespaces for this document.
    void
    This method sets the default name space URI string for this document.
    void
    setDocType(String doctype, String pub, String syst)
    Specifies a DOCTYPE for the XML document.
    void
    setEncoding(String encoding)
    (Re)set the encoding type.
    void
    setNamespace(String prefix, String uri)
    Add a namespace mapping to the document.
    void
    Add special elements to the XML header, such as processing instructions or comments that must precede the root element.
    protected static String
    strip a <?xml.....?> header from an XML document.
    Convert the document to the actual XML document String, without using character encoding.
    toRawXmlString(boolean useIndentation)
    Convert the document to the actual XML document String, without using character encoding.
    toRawXmlString(boolean addEncodingDecl, boolean useIndentation)
    Convert the document to the actual XML document String, with or without character encoding declaration (but see the description of the returned string!).
    toRawXmlString(boolean addEncodingDecl, boolean useIndentation, boolean sortAttributes)
    Convert the document to the actual XML document String, with or without character encoding declaration (but see the description of the returned string!).
    protected String
    toRawXmlStringImpl(boolean withEncDecl, boolean useIndentation, boolean sortAttributes)
    Internal method that actually creates the raw XML document.
    void
    Write the XML document to a OutputStream (indented).
    void
    writeXml(OutputStream os, boolean useIndentation)
    Write the XML document to a OutputStream.

    Methods inherited from class java.lang.Object

    clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
  • Constructor Details

    • XmlGenerator

      public XmlGenerator()
      Constructs a new empty generator.
    • XmlGenerator

      public XmlGenerator(IXmlElement root)
      shortcut constructor, to perform the most used steps in one go:
      • creates an XMLGenerator
      • calls beginDocument
      • adds the given element as root node
      • calls endDocument
      Usually you'll create the XML structure using XMLNewElement objects, and then create an XMLGenerator to write the XML source. This constructor makes that last step easy.
      Parameters:
      root - The root element of the XML document.
  • Method Details

    • escape

      protected static void escape(String str, StringBuffer outputBuffer)
      internal escape method operating on a StringBuffer.
      Parameters:
      str - The string that should be escaped.
      outputBuffer - The buffer the escaped string should be added to.
    • stripXMLheader

      protected static String stripXMLheader(String xmldoc)
      strip a <?xml.....?> header from an XML document.
      Parameters:
      xmldoc - The XML string from which the header should be stripped.
      Returns:
      The XML string without the header.
      Throws:
      IllegalArgumentException - when there is no correct XML header to strip
    • clear

      public void clear()
      Clear everything, the generator can now be reused for a new document.
    • beginDocument

      public void beginDocument()
      Begins a new XML document.
      See Also:
    • beginDocument

      public void beginDocument(String encoding)
      Begins a new XML document with given encoding type.
      Parameters:
      encoding - The encoding type of the document.
      See Also:
    • setNamespace

      public void setNamespace(String prefix, String uri)
      Add a namespace mapping to the document.
      Parameters:
      prefix - prefix of the namespace
      uri - uri of the namespace
    • getEncoding

      public String getEncoding()
      returns the current character encoding that will be used for XML generation.
      Returns:
      the current character encoding that will be used for XML generation.
    • setEncoding

      public void setEncoding(String encoding)
      (Re)set the encoding type. Supported by Java are usually US-ASCII, ISO-8859-1 (iso-latin-1), UTF-8, UTF-16, UTF-16BE, UTF-16LE, UNICODE. (and on windows: Cp1252)
      Parameters:
      encoding - The encoding type of the document.
    • getDefaultNamespace

      public String getDefaultNamespace()
      Returns the current default namespace uri.
      Returns:
      the current default namespace uri
    • setDefaultNamespace

      public void setDefaultNamespace(String uri)
      This method sets the default name space URI string for this document.
      Parameters:
      uri - the URI of the default namespace to use
    • getNamespaces

      public Map<String,String> getNamespaces()
      Returns the current table of namespaces for this document.
      Returns:
      the namespaces for this document (prefix-to-uri map)
    • setDocType

      public void setDocType(String doctype, String pub, String syst)
      Specifies a DOCTYPE for the XML document.
      Parameters:
      doctype - the doctype (required - must be the same as the root node)
      pub - public entity (may be null)
      syst - system entity (may be null, but only if public is null too.)
      Throws:
      XmlGenerateException - This exception is thrown when the generator represents an XML fragment.
    • setSpecialElements

      public void setSpecialElements(XmlNewAbstractSpecialElt[] specialElts)
      Add special elements to the XML header, such as processing instructions or comments that must precede the root element.
      Parameters:
      specialElts - the array of special element nodes, or null to clear it.
    • beginDocumentFragment

      public void beginDocumentFragment(int indentLevel)
      Begin a new XML document fragment (a part of a full document, without header).
      Parameters:
      indentLevel - the indentation level for this document fragment
      See Also:
    • beginDocumentFragment

      public void beginDocumentFragment()
      Begins a new XML document fragment (a part of a full document, without header).
      See Also:
    • endDocument

      public void endDocument()
      Ends the XML document, it is now finished and can be converted to an XML string for instance.
      Throws:
      XmlGenerateException - if called at wrong moment
    • addChild

      public void addChild(IXmlElement elt)
      Adds a new element to the XML document. If you're creating an XML document, you can only add one element (the root). If you're creating an XML document fragment, you can add many elements. You can always add any number of comment elements.
      Parameters:
      elt - the element to add.
      Throws:
      XmlGenerateException - if attempting to create invalid XML
    • addChild

      public void addChild(XmlGenerator docFragment)
      Adds a document fragment to another document.
      Parameters:
      docFragment - the document fragment to add.
      Throws:
      XmlGenerateException - if attempting to create invalid XML
    • addAsChildrenTo

      public void addAsChildrenTo(IXmlElement parent)
      add this document as a document fragment to another parent element.
      Parameters:
      parent - The parent element where all elements should be added to.
      Throws:
      XmlGenerateException - when an exception occurs generating XML
    • toRawXmlString

      public String toRawXmlString()
      Convert the document to the actual XML document String, without using character encoding. Also, no character coding declaration will be present in the XML string! Whitespace indentation is used for pretty printing.
      Returns:
      the XML document as String. The character encoding has not been applied (i.e. you get the XML as a normal Java unicode String object)
      Throws:
      XmlGenerateException - when called before the document has been ended by endDocument
    • toRawXmlString

      public String toRawXmlString(boolean useIndentation)
      Convert the document to the actual XML document String, without using character encoding. Also, no character coding declaration will be present in the XML string!
      Parameters:
      useIndentation - true to use whitespace indentation for pretty printing, false to avoid any whitespace between XML elements
      Returns:
      the XML document as String. The character encoding has not been applied (i.e. you get the XML as a normal Java unicode String object)
      Throws:
      XmlGenerateException - when called before the document has been ended by endDocument
    • toRawXmlString

      public String toRawXmlString(boolean addEncodingDecl, boolean useIndentation)
      Convert the document to the actual XML document String, with or without character encoding declaration (but see the description of the returned string!). When the addEncodingDecl parameter is true, the contents of the string will also be converted to the specified encoding.
      Parameters:
      addEncodingDecl - boolean indicating if the encoding declaration should be added to the XML string.
      useIndentation - true to use whitespace indentation for pretty printing, false to avoid any whitespace between XML elements
      Returns:
      the XML document as String.
      Throws:
      XmlGenerateException - when called before the document has been ended by endDocument
    • toRawXmlString

      public String toRawXmlString(boolean addEncodingDecl, boolean useIndentation, boolean sortAttributes)
      Convert the document to the actual XML document String, with or without character encoding declaration (but see the description of the returned string!). When the addEncodingDecl parameter is true, the contents of the string will also be converted to the specified encoding.
      Parameters:
      addEncodingDecl - boolean indicating if the encoding declaration should be added to the XML string.
      useIndentation - true to use whitespace indentation for pretty printing, false to avoid any whitespace between XML elements
      sortAttributes - true to use sort the attributes by name in alphabetic order.
      Returns:
      the XML document as String.
      Throws:
      XmlGenerateException - when called before the document has been ended by endDocument
    • toRawXmlStringImpl

      protected String toRawXmlStringImpl(boolean withEncDecl, boolean useIndentation, boolean sortAttributes)
      Internal method that actually creates the raw XML document. When the addEncodingDecl parameter is true, the contents of the string will also be converted to the specified encoding.
      Parameters:
      withEncDecl - use ENCODING declaration in the XML header
      useIndentation - true to use whitespace indentation for pretty printing, false to avoid any whitespace between XML elements
      sortAttributes - true to use sort the attributes in alphabetic order.
      Returns:
      the raw XML document.
      Throws:
      XmlGenerateException - when creation of XML failed
    • writeXml

      public void writeXml(OutputStream os) throws IOException
      Write the XML document to a OutputStream (indented). The required character encoding has been applied, if it is a full document and not a fragment. NOTE: it doesn't store the intermediate encoded byte array representation in memory- it directly streams it to the outputstream. This saves a lot of memory. (The -unencoded- String form is still generated in memory though)
      Parameters:
      os - Output stream the xml should be written to.
      Throws:
      IOException - in case of writing/encoding error
      XmlGenerateException - in case of XML conversion/structure error
    • writeXml

      public void writeXml(OutputStream os, boolean useIndentation) throws IOException
      Write the XML document to a OutputStream. The required character encoding has been applied, if it is a full document and not a fragment. NOTE: it doesn't store the intermediate encoded byte array representation in memory- it directly streams it to the outputstream. This saves a lot of memory. (The -unencoded- String form is still generated in memory though)
      Parameters:
      os - Output stream the xml should be written to.
      useIndentation - true to use whitespace indentation for pretty printing, false to avoid any whitespace between XML elements
      Throws:
      IOException - in case of writing/encoding error
      XmlGenerateException - in case of XML conversion/structure error