com.bristle.javalib.xml
Class XMLUtil

java.lang.Object
  extended by com.bristle.javalib.xml.XMLUtil

public class XMLUtil
extends Object

This class contains utility routines for manipulating XML.

Usage:
   - Some typical scenarios for using this class are:

     - To create an XML Document from scratch and convert it to a String:
           Document dom = XMLUtil.createEmptyDocument();
           Node xmlNode = XMLUtil.appendElement(dom, "Person");
           XMLUtil.appendElementContainingText(xmlNode, "Name", "John Smith");
           XMLUtil.appendElementContainingText(xmlNode, "Phone", "800-555-1212");
           String strXML = XMLUtil.serialize(dom);

     - To load and query an existing XML Document:
           Document dom = XMLUtil.loadDocumentFromURL
                                       ("http://www.xmlsource.com");
           String strName = XMLUtil.getTextNodeValueViaXPath
                                       (xmlNode, ".//Name");
           String strPhone = XMLUtil.getTextNodeValueViaXPath
                                       (xmlNode, "Phone");

     - To load and modify an existing XML Document:
           Document dom = XMLUtil.loadDocumentFromURL
                                       ("http://www.xmlsource.com");
           String strName = XMLUtil.setTextNodeValueViaXPath
                                       (xmlNode, ".//Name", "John Smith");
           String strPhone = XMLUtil.setTextNodeValueViaXPath
                                       (xmlNode, "Phone", "800-555-1212");

   - See the source code of the inner Tester class for more examples.
  
Assumptions:
Effects:
       - None.
Anticipated Changes:
Notes:
       - Pay particular attection to the distinction between the different
         XML DOM node types.  The names and comments in this class use these
         different terms very precisely: 
           Document    An entire XML DOM document
           DocumentFragment    
                       A fragment of an XML document.
           Element     An XML element or tag (an item in angle brackets)
           Text        A sequence of text stored in an Element
           Node        Could be any of the above, or an XML attribute, CDATA,
                       comment, document type, entity, etc.
         See the org.w3c.dom.Node documentation for details.            
       - The term "append" when used in method names in this class typically
         means "append a newly created child node to the specified node". 
Implementation Notes:
Portability Issues:
Revision History:
   $Log$


Nested Class Summary
static class XMLUtil.NoSuchXMLNodeException
          This exception is thrown when the specified XML node doesn't exist.
static class XMLUtil.Tester
          Each class contains a Tester inner class with a main() for easier unit testing.
 
Field Summary
static Node nodeINSERT_AFTER_LAST
          Constant for use as parameter to insertBefore.
 
Constructor Summary
XMLUtil()
           
 
Method Summary
static Element appendElement(Node xmlNode, String strName)
          Append a child Element to the specified Node.
static Element appendElementContainingText(Node xmlNode, String strName, String strText)
          Append a child Element containing a Text node to the specified Node.
static Text appendTextNode(Node xmlNode, String strText)
          Append a child Text node to the specified Node.
static Document createEmptyDocument()
          Creates an empty XML Document.
static String formatEndTag(String strTag)
          Format the end version of the specified XML tag.
static String formatStartTag(String strTag)
          Format the start version of the specified XML tag.
static String formatStartTagAndAttributes(String strTag, String strAttributes)
          Format the start version of the specified XML tag, and include a set of attributes.
static Element getFirstChildElement(Node xml)
          Returns the first child Element of a Node, or null if no child Element found.
static int getIntTextNodeValueViaXPath(Node xmlNode, String strXPath)
          Get the int value of the text node that is embedded in the node that is located at the specified XPath from the specified node, defaulting to 0 if the text node has an empty value.
static Element getOrAppendElement(Node xmlNode, String strName)
          Get the child Element with the specified name.
static void getOrAppendElementAndSetTextNodeValue(Node xmlNode, String strName, String strValue)
          Get the child Element with the specified name.
static Document getOwnerDocument(Node xmlNode)
          Get the owner document of the specified node.
static Element getRootElement(Document dom)
          Returns the root Element of a Document, or null if no root found.
static Document getSystemProperties()
          Get an XML Document containing all Java system properties.
static String getTextNodeValueOrEmptyStringViaXPath(Node xmlNode, String strXPath)
          Get the value of the text node that is embedded in the node that is located at the specified XPath from the specified node.
static String getTextNodeValueViaXPath(Node xmlNode, String strXPath)
          Get the value of the text node that is embedded in the node that is located at the specified XPath from the specified node.
static Node insertBefore(Node xmlParent, Node xmlNewChild, Node xmlRefChild)
          Inserts xmlNewChild as a child of xmlParent before the existing child xmlRefChild, or as the last child if xmlRefChild is null, copying the new Node and its entire subtree from a different Document if necessary.
static Document loadDocumentFromInputSource(InputSource inputSource)
          Load the specified URL into an XML Document.
static Document loadDocumentFromString(String strXML)
          Load the specified XML string into an XML Document.
static Document loadDocumentFromURL(String strURL)
          Load the specified URL into an XML Document.
static void removeAllChildren(Node xmlNode)
          Remove all child nodes from the specified Node.
static String serialize(Document xml)
          Serialize the XML Document into a string of XML.
static String serialize(DocumentFragment xml)
          Serialize the XML DocumentFragment into a string of XML.
static OutputStream serialize(DocumentFragment xml, OutputStream out)
          Serialize the XML DocumentFragment into the specified OutputStream, silently tolerating a null DocumentFragment.
static Writer serialize(DocumentFragment xml, Writer writer)
          Serialize the XML DocumentFragment into the specified Writer, silently tolerating a null DocumentFragment.
static OutputStream serialize(Document xml, OutputStream out)
          Serialize the XML Document into the specified OutputStream, silently tolerating a null Document.
static Writer serialize(Document xml, Writer writer)
          Serialize the XML Document into the specified Writer, silently tolerating a null Document.
static String serialize(Element xml)
          Serialize the XML Element into a string of XML.
static OutputStream serialize(Element xml, OutputStream out)
          Serialize the XML Element into the specified OutputStream, silently tolerating a null Element.
static Writer serialize(Element xml, Writer writer)
          Serialize the XML Element into the specified Writer, silently tolerating a null Element.
static String serializeChildElements(Node xml)
          Serialize the child Elements of the XML Node into a string of XML
static OutputStream serializeChildElements(Node xml, OutputStream out)
          Serialize the child Elements of the XML Node into the specified OutputStream, silently tolerating a null Node.
static Writer serializeChildElements(Node xml, Writer writer)
          Serialize the child Elements of the XML Node into the specified Writer, silently tolerating a null Node.
static void setNodeValueViaXPath(Node xmlNode, String strXPath, String strText)
          Set the value of the specified XML Node.
static void setTextNodeValueViaXPath(Node xmlNode, String strXPath, String strText)
          Set the value of the text node that is embedded in the node that is located at the specified XPath from the specified node.
static Document wrapThrowableInXML(Throwable e, Object objSource)
          Wraps the info from a Java Throwable in an XML Document.
static String wrapThrowableInXMLString(Throwable e, Object objSource)
          Wraps the info from a Java Throwable in an XML String.
static String wrapThrowableSafelyInXMLString(Throwable e, Object objSource)
          Wraps the info from a Java Throwable in an XML String, without risk of throwing another Throwable.
static Writer writeEndTag(Writer writer, String strTag)
          Write the end version of the specified XML tag to the specified Writer.
static Writer writeStartTag(Writer writer, String strTag)
          Write the start version of the specified XML tag to the specified Writer.
static Writer writeStartTagAndAttributes(Writer writer, String strTag, String strAttributes)
          Write the start version of the specified XML tag to the specified Writer, including an attribute string.
static Writer writeTagAndValue(Writer writer, String strTag, String strValue)
          Write the specified value, enclosed in the start and end versions of the specified XML tag, to the specified Writer.
 
Methods inherited from class java.lang.Object
equals, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
 

Field Detail

nodeINSERT_AFTER_LAST

public static final Node nodeINSERT_AFTER_LAST
Constant for use as parameter to insertBefore.

Constructor Detail

XMLUtil

public XMLUtil()
Method Detail

createEmptyDocument

public static Document createEmptyDocument()
Creates an empty XML Document.

Returns:
Empty XML Document.

loadDocumentFromURL

public static Document loadDocumentFromURL(String strURL)
                                    throws SAXException,
                                           IOException
Load the specified URL into an XML Document.
Anticipated Changes:
      None.

Parameters:
strURL - URL containing XML to load.
Returns:
XML Document.
Throws:
SAXException - When URL contains invalid XML.
IOException - When an error occurs reading from the URL.

loadDocumentFromInputSource

public static Document loadDocumentFromInputSource(InputSource inputSource)
                                            throws SAXException,
                                                   IOException
Load the specified URL into an XML Document.
Anticipated Changes:
      None.

Parameters:
inputSource - InputSource containing XML to load.
Returns:
XML Document.
Throws:
SAXException - When InputSource contains invalid XML.
IOException - When an error occurs reading from the InputSource.

loadDocumentFromString

public static Document loadDocumentFromString(String strXML)
                                       throws SAXException,
                                              IOException
Load the specified XML string into an XML Document.
Anticipated Changes:
      None.

Parameters:
strXML - String of XML to load.
Returns:
XML Document.
Throws:
SAXException - When string contains invalid XML.
IOException - When an error occurs reading from the string.

getOwnerDocument

public static Document getOwnerDocument(Node xmlNode)
Get the owner document of the specified node. If the node is itself a document, return it.

Parameters:
xmlNode - Node to get the owner document of.
Returns:
Document node.

appendTextNode

public static Text appendTextNode(Node xmlNode,
                                  String strText)
Append a child Text node to the specified Node.

Parameters:
xmlNode - Node to append to.
strText - String to put in text node.
Returns:
New text node.

appendElement

public static Element appendElement(Node xmlNode,
                                    String strName)
Append a child Element to the specified Node.

Parameters:
xmlNode - Node to append to.
strName - String to use as name of new Node.
Returns:
New Element.

appendElementContainingText

public static Element appendElementContainingText(Node xmlNode,
                                                  String strName,
                                                  String strText)
Append a child Element containing a Text node to the specified Node.

Parameters:
xmlNode - Node to append to.
strName - String to use as name of new Element.
strText - String to put in Text node.
Returns:
New Element.

wrapThrowableInXML

public static Document wrapThrowableInXML(Throwable e,
                                          Object objSource)
Wraps the info from a Java Throwable in an XML Document.

Parameters:
e - Throwable to wrap as XML.
objSource - Object throwing the Throwable.
Returns:
Document containing XML.

serialize

public static Writer serialize(Document xml,
                               Writer writer)
                        throws IOException
Serialize the XML Document into the specified Writer, silently tolerating a null Document.

Parameters:
xml - XML Document
writer - The Writer to serialize to.
Returns:
The specified Writer.
Throws:
IOException - When the Document can't be serialized.

serialize

public static OutputStream serialize(Document xml,
                                     OutputStream out)
                              throws IOException
Serialize the XML Document into the specified OutputStream, silently tolerating a null Document.

Parameters:
xml - XML Document
out - The OutputStream to serialize to.
Returns:
The specified OutputStream.
Throws:
IOException - When the Document can't be serialized.

serialize

public static String serialize(Document xml)
                        throws IOException
Serialize the XML Document into a string of XML.

Parameters:
xml - XML Document
Returns:
String of XML.
Throws:
IOException - When the Document can't be serialized.

serialize

public static Writer serialize(DocumentFragment xml,
                               Writer writer)
                        throws IOException
Serialize the XML DocumentFragment into the specified Writer, silently tolerating a null DocumentFragment.

Parameters:
xml - XML DocumentFragment
writer - The Writer to serialize to.
Returns:
The specified Writer.
Throws:
IOException - When the DocumentFragment can't be serialized.

serialize

public static OutputStream serialize(DocumentFragment xml,
                                     OutputStream out)
                              throws IOException
Serialize the XML DocumentFragment into the specified OutputStream, silently tolerating a null DocumentFragment.

Parameters:
xml - XML DocumentFragment
out - The OutputStream to serialize to.
Returns:
The specified OutputStream.
Throws:
IOException - When the DocumentFragment can't be serialized.

serialize

public static String serialize(DocumentFragment xml)
                        throws IOException
Serialize the XML DocumentFragment into a string of XML.

Parameters:
xml - XML DocumentFragment
Returns:
String of XML.
Throws:
IOException - When the DocumentFragment can't be serialized.

serialize

public static Writer serialize(Element xml,
                               Writer writer)
                        throws IOException
Serialize the XML Element into the specified Writer, silently tolerating a null Element.

Parameters:
xml - XML Element
writer - The Writer to serialize to.
Returns:
The specified Writer.
Throws:
IOException - When the Element can't be serialized.

serialize

public static OutputStream serialize(Element xml,
                                     OutputStream out)
                              throws IOException
Serialize the XML Element into the specified OutputStream, silently tolerating a null Element.

Parameters:
xml - XML Element
out - The OutputStream to serialize to.
Returns:
The specified OutputStream.
Throws:
IOException - When the Element can't be serialized.

serialize

public static String serialize(Element xml)
                        throws IOException
Serialize the XML Element into a string of XML.

Parameters:
xml - XML Element
Returns:
String of XML.
Throws:
IOException - When the Element can't be serialized.

serializeChildElements

public static Writer serializeChildElements(Node xml,
                                            Writer writer)
                                     throws IOException
Serialize the child Elements of the XML Node into the specified Writer, silently tolerating a null Node.

Parameters:
xml - XML Node
writer - The Writer to serialize to.
Returns:
The specified Writer.
Throws:
IOException - When the child Elements of the Node can't be serialized.

serializeChildElements

public static OutputStream serializeChildElements(Node xml,
                                                  OutputStream out)
                                           throws IOException
Serialize the child Elements of the XML Node into the specified OutputStream, silently tolerating a null Node.

Parameters:
xml - XML Node
out - The OutputStream to serialize to.
Returns:
The specified OutputStream.
Throws:
IOException - When the child Elements of the Node can't be serialized.

serializeChildElements

public static String serializeChildElements(Node xml)
                                     throws IOException
Serialize the child Elements of the XML Node into a string of XML

Parameters:
xml - XML Node
Returns:
The string of XML containing the child Elements.
Throws:
IOException - When the child Elements of the Node can't be serialized.

wrapThrowableInXMLString

public static String wrapThrowableInXMLString(Throwable e,
                                              Object objSource)
                                       throws IOException
Wraps the info from a Java Throwable in an XML String.

Parameters:
e - Throwable to wrap as XML.
objSource - Object throwing the Throwable.
Returns:
String containing XML.
Throws:
IOException - When the XML can't be serialized.

wrapThrowableSafelyInXMLString

public static String wrapThrowableSafelyInXMLString(Throwable e,
                                                    Object objSource)
Wraps the info from a Java Throwable in an XML String, without risk of throwing another Throwable. If unable to wrap the XML, it generates an XML string saying so.

Parameters:
e - Throwable to wrap as XML.
objSource - Object throwing the Throwable.
Returns:
String containing XML.

getTextNodeValueViaXPath

public static String getTextNodeValueViaXPath(Node xmlNode,
                                              String strXPath)
                                       throws TransformerException,
                                              XMLUtil.NoSuchXMLNodeException
Get the value of the text node that is embedded in the node that is located at the specified XPath from the specified node.

Parameters:
xmlNode - Node to search from.
strXPath - XPath to get from xmlNode to the desired node.
Returns:
String value of the text node.
Throws:
TransformerException - When the specified XPath is invalid.
XMLUtil.NoSuchXMLNodeException - When the node specified by the XPath doesn't exist.

getTextNodeValueOrEmptyStringViaXPath

public static String getTextNodeValueOrEmptyStringViaXPath(Node xmlNode,
                                                           String strXPath)
                                                    throws TransformerException
Get the value of the text node that is embedded in the node that is located at the specified XPath from the specified node. If not found, return the empty string instead.

Parameters:
xmlNode - Node to search from.
strXPath - XPath to get from xmlNode to the desired node.
Returns:
String value of the text node, or empty string.
Throws:
TransformerException - When the specified XPath is invalid.

getIntTextNodeValueViaXPath

public static int getIntTextNodeValueViaXPath(Node xmlNode,
                                              String strXPath)
                                       throws TransformerException,
                                              XMLUtil.NoSuchXMLNodeException,
                                              NumberFormatException
Get the int value of the text node that is embedded in the node that is located at the specified XPath from the specified node, defaulting to 0 if the text node has an empty value.

Parameters:
xmlNode - Node to search from.
strXPath - XPath to get from xmlNode to the desired node.
Returns:
int value of the text node.
Throws:
TransformerException - When the specified XPath is invalid.
XMLUtil.NoSuchXMLNodeException - When the node specified by the XPath doesn't exist.
NumberFormatException - When the value of the text node is not "" or an integer.

setTextNodeValueViaXPath

public static void setTextNodeValueViaXPath(Node xmlNode,
                                            String strXPath,
                                            String strText)
                                     throws TransformerException,
                                            XMLUtil.NoSuchXMLNodeException
Set the value of the text node that is embedded in the node that is located at the specified XPath from the specified node. If the node specified by the XPath exists, but the text node doesn't, create the text node.

Parameters:
xmlNode - Node to search from.
strXPath - XPath to get from xmlNode to the desired node.
strText - String to put in text node.
Throws:
TransformerException - When the specified XPath is invalid.
XMLUtil.NoSuchXMLNodeException - When the node specified by the XPath doesn't exist.

setNodeValueViaXPath

public static void setNodeValueViaXPath(Node xmlNode,
                                        String strXPath,
                                        String strText)
                                 throws TransformerException,
                                        XMLUtil.NoSuchXMLNodeException
Set the value of the specified XML Node.

Parameters:
xmlNode - Node to search from.
strXPath - XPath to get from xmlNode to the desired Node.
strText - New value of the node.
Throws:
TransformerException - When the specified XPath is invalid.
XMLUtil.NoSuchXMLNodeException - When the node specified by the XPath doesn't exist.

getOrAppendElement

public static Element getOrAppendElement(Node xmlNode,
                                         String strName)
                                  throws TransformerException
Get the child Element with the specified name. If not found, append a new child Element to the specified Node.

Parameters:
xmlNode - Node to append child to.
strName - Name of the Element to get or create.
Returns:
Element that was found or created.
Throws:
TransformerException - When an error occurs searching the XML via XPath, probably because of an invalid value for strName.

getOrAppendElementAndSetTextNodeValue

public static void getOrAppendElementAndSetTextNodeValue(Node xmlNode,
                                                         String strName,
                                                         String strValue)
                                                  throws TransformerException
Get the child Element with the specified name. If not found, append a new child Element to the specified Node. Then set the value of the Text node inside the child Element.

Parameters:
xmlNode - Node to append child to.
strName - Name of the Element to get or create.
strValue - String to put in text node.
Throws:
TransformerException - When an error occurs searching the XML via XPath, probably because of an invalid value for strName.

removeAllChildren

public static void removeAllChildren(Node xmlNode)
Remove all child nodes from the specified Node.

Parameters:
xmlNode - Node to remove from.

getFirstChildElement

public static Element getFirstChildElement(Node xml)
Returns the first child Element of a Node, or null if no child Element found.

Parameters:
xml - Node to find first child Element of
Returns:
The first child Element or null.

getRootElement

public static Element getRootElement(Document dom)
Returns the root Element of a Document, or null if no root found.

Parameters:
dom - Document to find root Element of
Returns:
The root Element or null.

insertBefore

public static Node insertBefore(Node xmlParent,
                                Node xmlNewChild,
                                Node xmlRefChild)
Inserts xmlNewChild as a child of xmlParent before the existing child xmlRefChild, or as the last child if xmlRefChild is null, copying the new Node and its entire subtree from a different Document if necessary.
 Note:  This is identical to org.w3c.dom.Node.insertBefore() except that 
        1.  It calls org.w3c.dom.Document.importNode() to copy the Node 
            and its subtree from another Document, if necessary to avoid 
            throwing an exception.
        2.  If xmlNewChild is an entire Document, it inserts the single 
            Element child of the Document (the root Element) instead of 
            the Document itself, to avoid throwing an exception.

Parameters:
xmlParent - Node to insert the child into
xmlNewChild - Node to insert as child
xmlRefChild - Existing child Node to insert before, or null.
Returns:
The inserted Node.

formatStartTag

public static String formatStartTag(String strTag)
Format the start version of the specified XML tag.

Parameters:
strTag - XML tag (without angle brackets).
Returns:
The formatted XML string.

formatStartTagAndAttributes

public static String formatStartTagAndAttributes(String strTag,
                                                 String strAttributes)
Format the start version of the specified XML tag, and include a set of attributes.

Parameters:
strTag - XML tag (without angle brackets).
strAttributes - Attributes to be included in the start tag.
Returns:
The formatted XML string.

formatEndTag

public static String formatEndTag(String strTag)
Format the end version of the specified XML tag.

Parameters:
strTag - XML tag (without angle brackets or slash).
Returns:
The formatted XML string.

writeStartTag

public static Writer writeStartTag(Writer writer,
                                   String strTag)
                            throws IOException
Write the start version of the specified XML tag to the specified Writer.

Parameters:
writer - Writer to write start tag to.
strTag - XML tag (without angle brackets).
Returns:
The specified Writer.
Throws:
IOException - When an error occurs writing to the Writer.

writeStartTagAndAttributes

public static Writer writeStartTagAndAttributes(Writer writer,
                                                String strTag,
                                                String strAttributes)
                                         throws IOException
Write the start version of the specified XML tag to the specified Writer, including an attribute string.

Parameters:
writer - Writer to write start tag to.
strTag - XML tag (without angle brackets).
strAttributes - Attributes to be included in the start tag.
Returns:
The specified Writer.
Throws:
IOException - When an error occurs writing to the Writer.

writeEndTag

public static Writer writeEndTag(Writer writer,
                                 String strTag)
                          throws IOException
Write the end version of the specified XML tag to the specified Writer.

Parameters:
writer - Writer to write end tag to.
strTag - XML tag (without angle brackets or slash).
Returns:
The specified Writer.
Throws:
IOException - When an error occurs writing to the Writer.

writeTagAndValue

public static Writer writeTagAndValue(Writer writer,
                                      String strTag,
                                      String strValue)
                               throws IOException
Write the specified value, enclosed in the start and end versions of the specified XML tag, to the specified Writer.

Parameters:
writer - Writer to write to.
strTag - XML tag (without angle brackets).
strValue - String value to enclose in XML tags.
Returns:
The specified Writer.
Throws:
IOException - When an error occurs writing to the Writer.

getSystemProperties

public static Document getSystemProperties()
Get an XML Document containing all Java system properties. Format of XML is: <SystemProps> <SystemProp> <PropName>xxx</PropName> <PropValue>xxx</PropValue> </SystemProp> ... </SystemProps>

Returns:
The XML Document