Class BaseXMLBuilder

  • Direct Known Subclasses:
    XMLBuilder, XMLBuilder2

    public abstract class BaseXMLBuilder
    extends Object
    Base abstract class for all XML Builder implementations. Most of the work is done here.
    Author:
    jmurty
    • Field Detail

      • failIfExternalEntityParsingCannotBeConfigured

        public static boolean failIfExternalEntityParsingCannotBeConfigured
        If true, the builder will raise an XMLBuilderRuntimeException if external general and parameter entities cannot be explicitly enabled or disabled.
    • Constructor Detail

      • BaseXMLBuilder

        protected BaseXMLBuilder​(Document xmlDocument)
        Construct a new builder object that wraps the given XML document. This constructor is for internal use only.
        Parameters:
        xmlDocument - an XML document that the builder will manage and manipulate.
      • BaseXMLBuilder

        protected BaseXMLBuilder​(Node myNode,
                                 Node parentNode)
        Construct a new builder object that wraps the given XML document and node. This constructor is for internal use only.
        Parameters:
        myNode - the XML node that this builder node will wrap. This node may be part of the XML document, or it may be a new element that is to be added to the document.
        parentNode - If not null, the given myElement will be appended as child node of the parentNode node.
    • Method Detail

      • enableOrDisableExternalEntityParsing

        protected static void enableOrDisableExternalEntityParsing​(DocumentBuilderFactory factory,
                                                                   boolean enableExternalEntities)
        Explicitly enable or disable the 'external-general-entities' and 'external-parameter-entities' features of the underlying DocumentBuilderFactory. TODO This is a naive approach that simply tries to apply all known feature name/URL values in turn until one succeeds, or none do.
        Parameters:
        factory - factory which will have external general and parameter entities enabled or disabled.
        enableExternalEntities - if true external entities will be explicitly enabled, otherwise they will be explicitly disabled.
      • createDocumentImpl

        protected static Document createDocumentImpl​(String name,
                                                     String namespaceURI,
                                                     boolean enableExternalEntities,
                                                     boolean isNamespaceAware)
                                              throws ParserConfigurationException,
                                                     FactoryConfigurationError
        Construct an XML Document with a default namespace with the given root element.
        Parameters:
        name - the name of the document's root element.
        namespaceURI - default namespace URI for document, ignored if null or empty.
        enableExternalEntities - enable external entities; beware of XML External Entity (XXE) injection.
        isNamespaceAware - enable or disable namespace awareness in the underlying DocumentBuilderFactory
        Returns:
        an XML Document.
        Throws:
        FactoryConfigurationError - xyz
        ParserConfigurationException - xyz
      • stripWhitespaceOnlyTextNodesImpl

        protected void stripWhitespaceOnlyTextNodesImpl()
                                                 throws XPathExpressionException
        Find and delete from the underlying Document any text nodes that contain nothing but whitespace, such as newlines and tab or space characters used to indent or pretty-print an XML document. Uses approach I documented on StackOverflow: http://stackoverflow.com/a/979606/4970
        Throws:
        XPathExpressionException - xyz
      • stripWhitespaceOnlyTextNodes

        public abstract BaseXMLBuilder stripWhitespaceOnlyTextNodes()
                                                             throws XPathExpressionException
        Find and delete from the underlying Document any text nodes that contain nothing but whitespace, such as newlines and tab or space characters used to indent or pretty-print an XML document. Uses approach I documented on StackOverflow: http://stackoverflow.com/a/979606/4970
        Returns:
        a builder node at the same location as before the operation.
        Throws:
        XPathExpressionException - xyz
      • importXMLBuilderImpl

        protected void importXMLBuilderImpl​(BaseXMLBuilder builder)
        Imports another BaseXMLBuilder document into this document at the current position. The entire document provided is imported.
        Parameters:
        builder - the BaseXMLBuilder document to be imported.
      • equals

        public boolean equals​(Object obj)
        Overrides:
        equals in class Object
        Returns:
        true if the XML Document and Element objects wrapped by this builder are equal to the other's wrapped objects.
      • getElement

        public Element getElement()
        Returns:
        the XML element wrapped by this builder node, or null if the builder node wraps the root Document node.
      • getDocument

        public Document getDocument()
        Returns:
        the XML document constructed by all builder nodes.
      • importXMLBuilder

        public abstract BaseXMLBuilder importXMLBuilder​(BaseXMLBuilder builder)
        Imports another XMLBuilder document into this document at the current position. The entire document provided is imported.
        Parameters:
        builder - the XMLBuilder document to be imported.
        Returns:
        a builder node at the same location as before the import, but now containing the entire document tree provided.
      • root

        public abstract BaseXMLBuilder root()
        Returns:
        the builder node representing the root element of the XML document.
      • xpathQuery

        public Object xpathQuery​(String xpath,
                                 QName type,
                                 NamespaceContext nsContext)
                          throws XPathExpressionException
        Return the result of evaluating an XPath query on the builder's DOM using the given namespace. Returns null if the query finds nothing, or finds a node that does not match the type specified by returnType.
        Parameters:
        xpath - an XPath expression
        type - the type the XPath is expected to resolve to, e.g: XPathConstants.NODE, XPathConstants.NODESET, XPathConstants.STRING.
        nsContext - a mapping of prefixes to namespace URIs that allows the XPath expression to use namespaces, or null for a non-namespaced document.
        Returns:
        a builder node representing the first Element that matches the XPath expression.
        Throws:
        XPathExpressionException - If the XPath is invalid, or if does not resolve to at least one Node.ELEMENT_NODE.
      • xpathFind

        public abstract BaseXMLBuilder xpathFind​(String xpath,
                                                 NamespaceContext nsContext)
                                          throws XPathExpressionException
        Find the first element in the builder's DOM matching the given XPath expression, where the expression may include namespaces if a NamespaceContext is provided.
        Parameters:
        xpath - An XPath expression that *must* resolve to an existing Element within the document object model.
        nsContext - a mapping of prefixes to namespace URIs that allows the XPath expression to use namespaces.
        Returns:
        a builder node representing the first Element that matches the XPath expression.
        Throws:
        XPathExpressionException - If the XPath is invalid, or if does not resolve to at least one Node.ELEMENT_NODE.
      • xpathFind

        public abstract BaseXMLBuilder xpathFind​(String xpath)
                                          throws XPathExpressionException
        Find the first element in the builder's DOM matching the given XPath expression.
        Parameters:
        xpath - An XPath expression that *must* resolve to an existing Element within the document object model.
        Returns:
        a builder node representing the first Element that matches the XPath expression.
        Throws:
        XPathExpressionException - If the XPath is invalid, or if does not resolve to at least one Node.ELEMENT_NODE.
      • xpathFindImpl

        protected Node xpathFindImpl​(String xpath,
                                     NamespaceContext nsContext)
                              throws XPathExpressionException
        Find the first element in the builder's DOM matching the given XPath expression, where the expression may include namespaces if a NamespaceContext is provided.
        Parameters:
        xpath - An XPath expression that *must* resolve to an existing Element within the document object model.
        nsContext - a mapping of prefixes to namespace URIs that allows the XPath expression to use namespaces.
        Returns:
        the first Element that matches the XPath expression.
        Throws:
        XPathExpressionException - If the XPath is invalid, or if does not resolve to at least one Node.ELEMENT_NODE.
      • lookupNamespaceURIImpl

        protected String lookupNamespaceURIImpl​(String name)
        Look up the namespace matching the current builder node's qualified name prefix (if any) or the document's default namespace.
        Parameters:
        name - the name of the XML element.
        Returns:
        The namespace URI, or null if none applies.
      • elementImpl

        protected Element elementImpl​(String name,
                                      String namespaceURI)
        Add a named and namespaced XML element to the document as a child of this builder's node.
        Parameters:
        name - the name of the XML element.
        namespaceURI - a namespace URI
        Returns:
        xyz
        Throws:
        IllegalStateException - if you attempt to add a child element to an XML node that already contains a text node value.
      • element

        public abstract BaseXMLBuilder element​(String name)
        Add a named XML element to the document as a child of this builder node, and return the builder node representing the new child. When adding an element to a namespaced document, the new node will be assigned a namespace matching it's qualified name prefix (if any) or the document's default namespace. NOTE: If the element has a prefix that does not match any known namespaces, the element will be created without any namespace.
        Parameters:
        name - the name of the XML element.
        Returns:
        a builder node representing the new child.
        Throws:
        IllegalStateException - if you attempt to add a child element to an XML node that already contains a text node value.
      • elem

        public abstract BaseXMLBuilder elem​(String name)
        Synonym for element(String).
        Parameters:
        name - the name of the XML element.
        Returns:
        a builder node representing the new child.
        Throws:
        IllegalStateException - if you attempt to add a child element to an XML node that already contains a text node value.
      • e

        public abstract BaseXMLBuilder e​(String name)
        Synonym for element(String).
        Parameters:
        name - the name of the XML element.
        Returns:
        a builder node representing the new child.
        Throws:
        IllegalStateException - if you attempt to add a child element to an XML node that already contains a text node value.
      • element

        public abstract BaseXMLBuilder element​(String name,
                                               String namespaceURI)
        Add a named and namespaced XML element to the document as a child of this builder node, and return the builder node representing the new child.
        Parameters:
        name - the name of the XML element.
        namespaceURI - a namespace URI
        Returns:
        a builder node representing the new child.
        Throws:
        IllegalStateException - if you attempt to add a child element to an XML node that already contains a text node value.
      • elementBefore

        public abstract BaseXMLBuilder elementBefore​(String name)
        Add a named XML element to the document as a sibling element that precedes the position of this builder node, and return the builder node representing the new child. When adding an element to a namespaced document, the new node will be assigned a namespace matching it's qualified name prefix (if any) or the document's default namespace. NOTE: If the element has a prefix that does not match any known namespaces, the element will be created without any namespace.
        Parameters:
        name - the name of the XML element.
        Returns:
        a builder node representing the new child.
        Throws:
        IllegalStateException - if you attempt to add a sibling element to a node where there are already one or more siblings that are text nodes.
      • elementBefore

        public abstract BaseXMLBuilder elementBefore​(String name,
                                                     String namespaceURI)
        Add a named and namespaced XML element to the document as a sibling element that precedes the position of this builder node, and return the builder node representing the new child.
        Parameters:
        name - the name of the XML element.
        namespaceURI - a namespace URI
        Returns:
        a builder node representing the new child.
        Throws:
        IllegalStateException - if you attempt to add a sibling element to a node where there are already one or more siblings that are text nodes.
      • attribute

        public abstract BaseXMLBuilder attribute​(String name,
                                                 String value)
        Add a named attribute value to the element represented by this builder node, and return the node representing the element to which the attribute was added (not the new attribute node).
        Parameters:
        name - the attribute's name.
        value - the attribute's value.
        Returns:
        the builder node representing the element to which the attribute was added.
      • attr

        public abstract BaseXMLBuilder attr​(String name,
                                            String value)
        Parameters:
        name - the attribute's name.
        value - the attribute's value.
        Returns:
        the builder node representing the element to which the attribute was added.
      • a

        public abstract BaseXMLBuilder a​(String name,
                                         String value)
        Parameters:
        name - the attribute's name.
        value - the attribute's value.
        Returns:
        the builder node representing the element to which the attribute was added.
      • text

        public abstract BaseXMLBuilder text​(String value,
                                            boolean replaceText)
        Add or replace the text value of an element represented by this builder node, and return the node representing the element to which the text was added (not the new text node).
        Parameters:
        value - the text value to set or add to the element.
        replaceText - if True any existing text content of the node is replaced with the given text value, if the given value is appended to any existing text.
        Returns:
        the builder node representing the element to which the text was added.
      • text

        public abstract BaseXMLBuilder text​(String value)
        Add a text value to the element represented by this builder node, and return the node representing the element to which the text was added (not the new text node).
        Parameters:
        value - the text value to add to the element.
        Returns:
        the builder node representing the element to which the text was added.
      • t

        public abstract BaseXMLBuilder t​(String value)
        Synonym for text(String).
        Parameters:
        value - the text value to add to the element.
        Returns:
        the builder node representing the element to which the text was added.
      • elementBeforeImpl

        protected Element elementBeforeImpl​(String name)
        Add a named XML element to the document as a sibling element that precedes the position of this builder node. When adding an element to a namespaced document, the new node will be assigned a namespace matching it's qualified name prefix (if any) or the document's default namespace. NOTE: If the element has a prefix that does not match any known namespaces, the element will be created without any namespace.
        Parameters:
        name - the name of the XML element.
        Returns:
        xyz
        Throws:
        IllegalStateException - if you attempt to add a sibling element to a node where there are already one or more siblings that are text nodes.
      • elementBeforeImpl

        protected Element elementBeforeImpl​(String name,
                                            String namespaceURI)
        Add a named and namespaced XML element to the document as a sibling element that precedes the position of this builder node.
        Parameters:
        name - the name of the XML element.
        namespaceURI - a namespace URI
        Returns:
        xyz
        Throws:
        IllegalStateException - if you attempt to add a sibling element to a node where there are already one or more siblings that are text nodes.
      • attributeImpl

        protected void attributeImpl​(String name,
                                     String value)
        Add a named attribute value to the element for this builder node.
        Parameters:
        name - the attribute's name.
        value - the attribute's value.
      • textImpl

        protected void textImpl​(String value,
                                boolean replaceText)
        Add or replace the text value of an element for this builder node.
        Parameters:
        value - the text value to set or add to the element.
        replaceText - if True any existing text content of the node is replaced with the given text value, if the given value is appended to any existing text.
      • cdataImpl

        protected void cdataImpl​(String data)
        Add a CDATA node with String content to the element for this builder node.
        Parameters:
        data - the String value that will be added to a CDATA element.
      • cdataImpl

        protected void cdataImpl​(byte[] data)
        Add a CDATA node with Base64-encoded byte data content to the element for this builder node.
        Parameters:
        data - the data value that will be Base64-encoded and added to a CDATA element.
      • commentImpl

        protected void commentImpl​(String comment)
        Add a comment to the element represented by this builder node.
        Parameters:
        comment - the comment to add to the element.
      • instructionImpl

        protected void instructionImpl​(String target,
                                       String data)
        Add an instruction to the element represented by this builder node.
        Parameters:
        target - the target value for the instruction.
        data - the data value for the instruction
      • insertInstructionImpl

        protected void insertInstructionImpl​(String target,
                                             String data)
        Insert an instruction before the element represented by this builder node.
        Parameters:
        target - the target value for the instruction.
        data - the data value for the instruction
      • referenceImpl

        protected void referenceImpl​(String name)
        Add a reference to the element represented by this builder node.
        Parameters:
        name - the name value for the reference.
      • namespaceImpl

        protected void namespaceImpl​(String prefix,
                                     String namespaceURI)
        Add an XML namespace attribute to this builder's element node.
        Parameters:
        prefix - a prefix for the namespace URI within the document, may be null or empty in which case a default "xmlns" attribute is created.
        namespaceURI - a namespace uri
      • namespaceImpl

        protected void namespaceImpl​(String namespaceURI)
        Add an XML namespace attribute to this builder's element node without a prefix.
        Parameters:
        namespaceURI - a namespace uri
      • cdata

        public abstract BaseXMLBuilder cdata​(String data)
        Add a CDATA node with String content to the element represented by this builder node, and return the node representing the element to which the data was added (not the new CDATA node).
        Parameters:
        data - the String value that will be added to a CDATA element.
        Returns:
        the builder node representing the element to which the data was added.
      • data

        public abstract BaseXMLBuilder data​(String data)
        Synonym for cdata(String).
        Parameters:
        data - the String value that will be added to a CDATA element.
        Returns:
        the builder node representing the element to which the data was added.
      • d

        public abstract BaseXMLBuilder d​(String data)
        Synonym for cdata(String).
        Parameters:
        data - the String value that will be added to a CDATA element.
        Returns:
        the builder node representing the element to which the data was added.
      • cdata

        public abstract BaseXMLBuilder cdata​(byte[] data)
        Add a CDATA node with Base64-encoded byte data content to the element represented by this builder node, and return the node representing the element to which the data was added (not the new CDATA node).
        Parameters:
        data - the data value that will be Base64-encoded and added to a CDATA element.
        Returns:
        the builder node representing the element to which the data was added.
      • data

        public abstract BaseXMLBuilder data​(byte[] data)
        Synonym for cdata(byte[]).
        Parameters:
        data - the data value that will be Base64-encoded and added to a CDATA element.
        Returns:
        the builder node representing the element to which the data was added.
      • d

        public abstract BaseXMLBuilder d​(byte[] data)
        Synonym for cdata(byte[]).
        Parameters:
        data - the data value that will be Base64-encoded and added to a CDATA element.
        Returns:
        the builder node representing the element to which the data was added.
      • comment

        public abstract BaseXMLBuilder comment​(String comment)
        Add a comment to the element represented by this builder node, and return the node representing the element to which the comment was added (not the new comment node).
        Parameters:
        comment - the comment to add to the element.
        Returns:
        the builder node representing the element to which the comment was added.
      • cmnt

        public abstract BaseXMLBuilder cmnt​(String comment)
        Synonym for comment(String).
        Parameters:
        comment - the comment to add to the element.
        Returns:
        the builder node representing the element to which the comment was added.
      • c

        public abstract BaseXMLBuilder c​(String comment)
        Synonym for comment(String).
        Parameters:
        comment - the comment to add to the element.
        Returns:
        the builder node representing the element to which the comment was added.
      • instruction

        public abstract BaseXMLBuilder instruction​(String target,
                                                   String data)
        Add an instruction to the element represented by this builder node, and return the node representing the element to which the instruction was added (not the new instruction node).
        Parameters:
        target - the target value for the instruction.
        data - the data value for the instruction
        Returns:
        the builder node representing the element to which the instruction was added.
      • inst

        public abstract BaseXMLBuilder inst​(String target,
                                            String data)
        Parameters:
        target - the target value for the instruction.
        data - the data value for the instruction
        Returns:
        the builder node representing the element to which the instruction was added.
      • i

        public abstract BaseXMLBuilder i​(String target,
                                         String data)
        Parameters:
        target - the target value for the instruction.
        data - the data value for the instruction
        Returns:
        the builder node representing the element to which the instruction was added.
      • insertInstruction

        public abstract BaseXMLBuilder insertInstruction​(String target,
                                                         String data)
        Insert an instruction before the element represented by this builder node, and return the node representing that same element (not the new instruction node).
        Parameters:
        target - the target value for the instruction.
        data - the data value for the instruction
        Returns:
        the builder node representing the element before which the instruction was inserted.
      • reference

        public abstract BaseXMLBuilder reference​(String name)
        Add a reference to the element represented by this builder node, and return the node representing the element to which the reference was added (not the new reference node).
        Parameters:
        name - the name value for the reference.
        Returns:
        the builder node representing the element to which the reference was added.
      • ref

        public abstract BaseXMLBuilder ref​(String name)
        Synonym for reference(String).
        Parameters:
        name - the name value for the reference.
        Returns:
        the builder node representing the element to which the reference was added.
      • r

        public abstract BaseXMLBuilder r​(String name)
        Synonym for reference(String).
        Parameters:
        name - the name value for the reference.
        Returns:
        the builder node representing the element to which the reference was added.
      • namespace

        public abstract BaseXMLBuilder namespace​(String prefix,
                                                 String namespaceURI)
        Add an XML namespace attribute to this builder's element node.
        Parameters:
        prefix - a prefix for the namespace URI within the document, may be null or empty in which case a default "xmlns" attribute is created.
        namespaceURI - a namespace uri
        Returns:
        the builder node representing the element to which the attribute was added.
      • ns

        public abstract BaseXMLBuilder ns​(String prefix,
                                          String namespaceURI)
        Parameters:
        prefix - a prefix for the namespace URI within the document, may be null or empty in which case a default xmlns attribute is created.
        namespaceURI - a namespace uri
        Returns:
        the builder node representing the element to which the attribute was added.
      • namespace

        public abstract BaseXMLBuilder namespace​(String namespaceURI)
        Add an XML namespace attribute to this builder's element node without a prefix.
        Parameters:
        namespaceURI - a namespace uri
        Returns:
        the builder node representing the element to which the attribute was added.
      • ns

        public abstract BaseXMLBuilder ns​(String namespaceURI)
        Synonym for namespace(String).
        Parameters:
        namespaceURI - a namespace uri
        Returns:
        the builder node representing the element to which the attribute was added.
      • up

        public abstract BaseXMLBuilder up​(int steps)
        Return the builder node representing the nth ancestor element of this node, or the root node if n exceeds the document's depth.
        Parameters:
        steps - the number of parent elements to step over while navigating up the chain of node ancestors. A steps value of 1 will find a node's parent, 2 will find its grandparent etc.
        Returns:
        the nth ancestor of this node, or the root node if this is reached before the nth parent is found.
      • up

        public abstract BaseXMLBuilder up()
        Return the builder node representing the parent of the current node.
        Returns:
        the parent of this node, or the root node if this method is called on the root node.
      • document

        public abstract BaseXMLBuilder document()
        BEWARE: The builder returned by this method represents a Document node, not an Element node as is usually the case, so attempts to use the attribute or namespace methods on this builder will likely fail.
        Returns:
        the builder node representing the root XML document.
      • upImpl

        protected Node upImpl​(int steps)
        Return the Document node representing the nth ancestor element of this node, or the root node if n exceeds the document's depth.
        Parameters:
        steps - the number of parent elements to step over while navigating up the chain of node ancestors. A steps value of 1 will find a node's parent, 2 will find its grandparent etc.
        Returns:
        the nth ancestor of this node, or the root node if this is reached before the nth parent is found.
      • assertElementContainsNoOrWhitespaceOnlyTextNodes

        protected void assertElementContainsNoOrWhitespaceOnlyTextNodes​(Node anXmlElement)
        Parameters:
        anXmlElement - xyz
        Throws:
        IllegalStateException - if the current element contains any child text nodes that aren't pure whitespace. We allow whitespace so parsed XML documents containing indenting or pretty-printing can still be amended, per issue #17.
      • toWriter

        public void toWriter​(boolean wholeDocument,
                             Writer writer,
                             Properties outputProperties)
                      throws TransformerException
        Serialize either the specific Element wrapped by this BaseXMLBuilder, or its entire XML document, to the given writer using the default TransformerFactory and Transformer classes. If output options are provided, these options are provided to the Transformer serializer.
        Parameters:
        wholeDocument - if true the whole XML document (i.e. the document root) is serialized, if false just the current Element and its descendants are serialized.
        writer - a writer to which the serialized document is written.
        outputProperties - settings for the Transformer serializer. This parameter may be null or an empty Properties object, in which case the default output properties will be applied.
        Throws:
        TransformerException - xyz
      • toWriter

        public void toWriter​(Writer writer,
                             Properties outputProperties)
                      throws TransformerException
        Serialize the XML document to the given writer using the default TransformerFactory and Transformer classes. If output options are provided, these options are provided to the Transformer serializer.
        Parameters:
        writer - a writer to which the serialized document is written.
        outputProperties - settings for the Transformer serializer. This parameter may be null or an empty Properties object, in which case the default output properties will be applied.
        Throws:
        TransformerException - xyz
      • asString

        public String asString​(Properties outputProperties)
                        throws TransformerException
        Serialize the XML document to a string by delegating to the toWriter(Writer, Properties) method. If output options are provided, these options are provided to the Transformer serializer.
        Parameters:
        outputProperties - settings for the Transformer serializer. This parameter may be null or an empty Properties object, in which case the default output properties will be applied.
        Returns:
        the XML document as a string
        Throws:
        TransformerException - xyz
      • elementAsString

        public String elementAsString​(Properties outputProperties)
                               throws TransformerException
        Serialize the current XML Element and its descendants to a string by delegating to the toWriter(Writer, Properties) method. If output options are provided, these options are provided to the Transformer serializer.
        Parameters:
        outputProperties - settings for the Transformer serializer. This parameter may be null or an empty Properties object, in which case the default output properties will be applied.
        Returns:
        the XML document as a string
        Throws:
        TransformerException - xyz
      • asString

        public String asString()
                        throws TransformerException
        Serialize the XML document to a string excluding the XML declaration.
        Returns:
        the XML document as a string without the XML declaration at the beginning of the output.
        Throws:
        TransformerException - xyz
      • elementAsString

        public String elementAsString()
                               throws TransformerException
        Serialize the current XML Element and its descendants to a string excluding the XML declaration.
        Returns:
        the XML document as a string without the XML declaration at the beginning of the output.
        Throws:
        TransformerException - xyz
      • buildDocumentNamespaceContext

        protected NamespaceContextImpl buildDocumentNamespaceContext()
        Returns:
        a namespace context containing the prefixes and namespace URI's used within this builder's document, to assist in running namespace-aware XPath queries against the document.
      • getPrefixFromQualifiedName

        protected String getPrefixFromQualifiedName​(String qualifiedName)