com.jamesmurty.utils
Class XMLBuilder

java.lang.Object
  extended by com.jamesmurty.utils.XMLBuilder

public class XMLBuilder
extends Object

XML Builder is a utility that creates simple XML documents using relatively sparse Java code. It is intended to allow for quick and painless creation of XML documents where you might otherwise be tempted to use concatenated strings, rather than face the tedium and verbosity of coding with JAXP (http://jaxp.dev.java.net/).

Internally, XML Builder uses JAXP to build a standard W3C Document model (DOM) that you can easily export as a string, or access and manipulate further if you have special requirements.

The XMLBuilder class serves as a wrapper of Element nodes, and provides a number of utility methods that make it simple to manipulate the underlying element and the document to which it belongs. In essence, this class performs dual roles: it represents a specific XML node, and also allows manipulation of the entire underlying XML document. The platform's default DocumentBuilderFactory and DocumentBuilder classes are used to build the document.

Author:
James Murty

Constructor Summary
protected XMLBuilder(Document xmlDocument)
          Construct a new builder object that wraps the given XML document.
protected XMLBuilder(Node myNode, Node parentNode)
          Construct a new builder object that wraps the given XML document and node.
 
Method Summary
 XMLBuilder a(String name, String value)
          Synonym for attribute(String, String).
protected  void assertElementHasNoTextNodes(Node anXmlElement)
           
 String asString()
          Serialize the XML document to a string excluding the XML declaration.
 String asString(Properties outputProperties)
          Serialize the XML document to a string by delegating to the toWriter(Writer, Properties) method.
 XMLBuilder attr(String name, String value)
          Synonym for attribute(String, String).
 XMLBuilder 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).
 NamespaceContextImpl buildDocumentNamespaceContext()
           
 XMLBuilder c(String comment)
          Synonym for comment(String).
 XMLBuilder 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).
 XMLBuilder 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).
 XMLBuilder cmnt(String comment)
          Synonym for comment(String).
 XMLBuilder 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).
static XMLBuilder create(String name)
          Construct a builder for new XML document.
static XMLBuilder create(String name, String namespaceURI)
          Construct a builder for new XML document with a default namespace.
 XMLBuilder d(byte[] data)
          Synonym for cdata(byte[]).
 XMLBuilder d(String data)
          Synonym for cdata(String).
 XMLBuilder data(byte[] data)
          Synonym for cdata(byte[]).
 XMLBuilder data(String data)
          Synonym for cdata(String).
 XMLBuilder document()
          BEWARE: The builder returned by this method respresents 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.
 XMLBuilder e(String name)
          Synonym for element(String).
 XMLBuilder elem(String name)
          Synonym for element(String).
 XMLBuilder 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.
 XMLBuilder 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.
 String elementAsString()
          Serialize the current XML Element and its descendants to a string excluding the XML declaration.
 String elementAsString(Properties outputProperties)
          Serialize the current XML Element and its descendants to a string by delegating to the toWriter(Writer, Properties) method.
 XMLBuilder 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.
 XMLBuilder 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.
 boolean equals(Object obj)
           
 Document getDocument()
           
 Element getElement()
           
protected  String getPrefixFromQualifiedName(String qualifiedName)
           
 XMLBuilder i(String target, String data)
          Synonym for instruction(String, String).
 XMLBuilder importXMLBuilder(XMLBuilder builder)
          Imports another XMLBuilder document into this document at the current position.
 XMLBuilder 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).
 XMLBuilder inst(String target, String data)
          Synonym for instruction(String, String).
 XMLBuilder 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).
 XMLBuilder namespace(String namespaceURI)
          Add an XML namespace attribute to this builder's element node without a prefix.
 XMLBuilder namespace(String prefix, String namespaceURI)
          Add an XML namespace attribute to this builder's element node.
 XMLBuilder ns(String namespaceURI)
          Synonym for namespace(String).
 XMLBuilder ns(String prefix, String namespaceURI)
          Synonym for namespace(String, String).
static XMLBuilder parse(InputSource inputSource)
          Construct a builder from an existing XML document.
 XMLBuilder r(String name)
          Synonym for reference(String).
 XMLBuilder ref(String name)
          Synonym for reference(String).
 XMLBuilder 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).
 XMLBuilder root()
           
 XMLBuilder t(String value)
          Synonym for text(String).
 XMLBuilder 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).
 XMLBuilder 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).
 void toWriter(boolean wholeDocument, Writer writer, Properties outputProperties)
          Serialize either the specific Element wrapped by this XMLBuilder, or its entire XML document, to the given writer using the default TransformerFactory and Transformer classes.
 void toWriter(Writer writer, Properties outputProperties)
          Serialize the XML document to the given writer using the default TransformerFactory and Transformer classes.
 XMLBuilder up()
          Return the builder node representing the parent of the current node.
 XMLBuilder 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.
 XMLBuilder xpathFind(String xpath)
          Find the first element in the builder's DOM matching the given XPath expression.
 XMLBuilder xpathFind(String xpath, NamespaceContext nsContext)
          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.
 Object xpathQuery(String xpath, QName type)
          Return the result of evaluating an XPath query on the builder's DOM.
 Object xpathQuery(String xpath, QName type, NamespaceContext nsContext)
          Return the result of evaluating an XPath query on the builder's DOM using the given namespace.
 
Methods inherited from class java.lang.Object
clone, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
 

Constructor Detail

XMLBuilder

protected XMLBuilder(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.

XMLBuilder

protected XMLBuilder(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

create

public static XMLBuilder create(String name,
                                String namespaceURI)
                         throws ParserConfigurationException,
                                FactoryConfigurationError
Construct a builder for new XML document with a default namespace. The document will be created with the given root element, and the builder returned by this method will serve as the starting-point for any further document additions.

Parameters:
name - the name of the document's root element.
namespaceURI - default namespace URI for document, ignored if null or empty.
Returns:
a builder node that can be used to add more nodes to the XML document.
Throws:
FactoryConfigurationError
ParserConfigurationException

create

public static XMLBuilder create(String name)
                         throws ParserConfigurationException,
                                FactoryConfigurationError
Construct a builder for new XML document. The document will be created with the given root element, and the builder returned by this method will serve as the starting-point for any further document additions.

Parameters:
name - the name of the document's root element.
Returns:
a builder node that can be used to add more nodes to the XML document.
Throws:
FactoryConfigurationError
ParserConfigurationException

parse

public static XMLBuilder parse(InputSource inputSource)
                        throws ParserConfigurationException,
                               SAXException,
                               IOException
Construct a builder from an existing XML document. The provided XML document will be parsed and an XMLBuilder object referencing the document's root element will be returned.

Parameters:
inputSource - an XML document input source that will be parsed into a DOM.
Returns:
a builder node that can be used to add more nodes to the XML document.
Throws:
ParserConfigurationException
FactoryConfigurationError
ParserConfigurationException
IOException
SAXException

importXMLBuilder

public XMLBuilder importXMLBuilder(XMLBuilder 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.

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.

document

public XMLBuilder document()
BEWARE: The builder returned by this method respresents 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.

root

public XMLBuilder root()
Returns:
the builder node representing the root element of the XML document. In other words, the same builder node returned by the initial create(String) or parse(InputSource) method.

getDocument

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

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.

xpathQuery

public Object xpathQuery(String xpath,
                         QName type)
                  throws XPathExpressionException
Return the result of evaluating an XPath query on the builder's DOM. 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
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 XMLBuilder 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 XMLBuilder 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.

element

public XMLBuilder 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 XMLBuilder 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 XMLBuilder 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 XMLBuilder 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 XMLBuilder 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 XMLBuilder 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 XMLBuilder 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 XMLBuilder attr(String name,
                       String value)
Synonym for attribute(String, String).

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 XMLBuilder a(String name,
                    String value)
Synonym for attribute(String, String).

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 XMLBuilder 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 XMLBuilder 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 XMLBuilder 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.

cdata

public XMLBuilder 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 XMLBuilder 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 XMLBuilder 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 XMLBuilder 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 XMLBuilder 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 XMLBuilder 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 XMLBuilder 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 XMLBuilder 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 XMLBuilder 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 XMLBuilder 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 XMLBuilder inst(String target,
                       String data)
Synonym for instruction(String, String).

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 XMLBuilder i(String target,
                    String data)
Synonym for instruction(String, String).

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 XMLBuilder 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 XMLBuilder 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 XMLBuilder 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 XMLBuilder 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 XMLBuilder 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 XMLBuilder ns(String prefix,
                     String namespaceURI)
Synonym for namespace(String, String).

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 XMLBuilder 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 XMLBuilder 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 XMLBuilder 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 XMLBuilder 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.

assertElementHasNoTextNodes

protected void assertElementHasNoTextNodes(Node anXmlElement)
Throws:
IllegalStateException - if the current element contains any child text nodes.

toWriter

public void toWriter(boolean wholeDocument,
                     Writer writer,
                     Properties outputProperties)
              throws TransformerException
Serialize either the specific Element wrapped by this XMLBuilder, 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

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

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

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

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

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

buildDocumentNamespaceContext

public 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)


Copyright © 2013. All Rights Reserved.