com.bowstreet.util
Class XmlUtil

java.lang.Object
  extended by com.bowstreet.util.XmlUtil

public class XmlUtil
extends java.lang.Object

The XmlUtil class consists exclusively of static methods that return XML objects. It provides methods for creating new XML objects from text representations. Once you have created an IXml, JDOM, or DOM object you can manipulate it with methods of the IXml, JDOM, or DOM interface respectively. In addition, it provides methods for creating alternative XML object representations that have been registered with the Factory. Methods are also provided to convert XML documents from one object representation to another. Below we use the term "document" to mean a string or a character stream of XML. When parsing XML documents into IXml, comments will not be preserved. If preserving comments is required, then an alternative representation such as DOM or JDOM should be used.

See Also:
IXml

Field Summary
static java.lang.String ALT_NAME_ATTRIBUTE
          Used in addition to "name" attribute to trigger full parse.
static java.lang.String HTMLCONTENT
           
static java.lang.String HTMLWRAPPER
           
static java.lang.String ID_ATTRIBUTE
          Used in addition to "name" & "_name_" attributes to trigger full parse.
 
Constructor Summary
XmlUtil()
           
 
Method Summary
static void copyAttributes(IXml schema, IXml data)
          Unsupported - INTERNAL USE ONLY
static void copyElementContents(IXml data, IXml schema)
          Unsupported - INTERNAL USE ONLY
static int countChildren(IXml parent)
          Counts the number of immediate children in parent
static int countChildren(IXml parent, java.lang.String filter)
          Counts the number of immediate children in parent with a specific name
static IXml create(java.lang.String name)
          Create a new, empty IXml element.
static IXml create(java.lang.String localname, java.lang.String prefix, java.lang.String namespaceURI)
          Create a new namespace-aware XML element with the specified localName and optional prefix and namespace URI.
static org.w3c.dom.Document createDOM(IXml source)
          Convert an IXml document into a DOM document and return it.
static org.w3c.dom.Document createDOM(java.io.Reader source)
          Parses an XML document from the specified Reader into a well formed DOM document (org.w3c.dom.Document).
static org.w3c.dom.Document createDOM(java.lang.String source)
          Parses an XML document from the specified String into a well formed DOM document (org.w3c.dom.Document).
static java.lang.Object createObject(java.lang.Object source, java.lang.String className)
          Convert an XML document into another representation and return it.
static IXml createRawTextElement(java.lang.String rawText)
          Create a section of "raw" text for use in conjunction with writeHtml, to include text with no escaping or quoting of special characters.
static IXml createXml(java.lang.Object source)
          Convert an XML document into an IXml document and return it.
static IXml findCommonAncestor(IXml node1, IXml node2)
          Finds the closest common ancestor to the two nodes.
static java.util.List<IXml> findElements(IXml x, java.lang.String xpath)
          Takes an xpath and returns a List of the matching elements.
static boolean hasMultipleRoots(java.lang.String xmlStr, java.lang.String rootName)
          This method detects if multiple roots are present in the given XML string.
static boolean isContainedWithin(IXml inner, IXml outer)
          Tests to see if inner (1st arg) is contained anywhere within outer, including recursively
static IXml lastChildOf(IXml parent)
          Finds the last child of an IXml element
static IXml parseHtml(java.io.Reader in)
          Parses an HTML document from the specified Reader into a well formed IXml object.
static IXml parseHtml(java.lang.String in)
          Parses an HTML document from the specified String into a well formed IXml object.
static IXml parseXml(java.io.Reader in)
          Parses an XML document from the specified Reader into a well formed IXml object.
static IXml parseXml(java.io.Reader in, boolean validateNamespacePrefixes)
          Parses an XML document from the specified Reader into a well formed IXml object.
static java.lang.Object parseXml(java.io.Reader source, java.lang.String className)
          Parses an XML document from the specified Reader into a well formed object of the specified class name.
static IXml parseXml(java.lang.String in)
          Parses an XML document from the specified String into a well formed IXml object.
static java.lang.Object parseXml(java.lang.String source, java.lang.String className)
          Parses an XML document from the specified String into a well formed object of the specified class name.
static java.lang.String prettyPrint(IXml xml)
           
static void removeAttributes(IXml node)
          Remove all attributes except those that define namespaces
static IXml safeParseXml(java.lang.String in)
          Parses an XML document from the specified String into a well formed IXml object.
static IXml safeParseXmlFromFile(java.lang.String filename)
          Parses an XML document from a file.
static java.lang.String toString(java.lang.Object source)
          Return the string representation of the specified XML document.
static void writeXml(java.lang.Object source, java.io.Writer out)
          Write an XML document (IXml, DOM, JDOM) to the specified Writer.
static void writeXml(java.lang.Object source, java.io.Writer out, boolean trimWhitespace)
          Same as writeXml, but with option to remove all whitespace from character data and between xml tags, which can be useful when needing to compare several XML documents.
 
Methods inherited from class java.lang.Object
equals, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
 

Field Detail

ALT_NAME_ATTRIBUTE

public static final java.lang.String ALT_NAME_ATTRIBUTE
Used in addition to "name" attribute to trigger full parse.

See Also:
Constant Field Values

HTMLCONTENT

public static final java.lang.String HTMLCONTENT
See Also:
Constant Field Values

HTMLWRAPPER

public static final java.lang.String HTMLWRAPPER
See Also:
Constant Field Values

ID_ATTRIBUTE

public static final java.lang.String ID_ATTRIBUTE
Used in addition to "name" & "_name_" attributes to trigger full parse.

See Also:
Constant Field Values
Constructor Detail

XmlUtil

public XmlUtil()
Method Detail

copyAttributes

public static void copyAttributes(IXml schema,
                                  IXml data)
Unsupported - INTERNAL USE ONLY


copyElementContents

public static void copyElementContents(IXml data,
                                       IXml schema)
Unsupported - INTERNAL USE ONLY


countChildren

public static int countChildren(IXml parent)
Counts the number of immediate children in parent

Parameters:
parent - The Parent to count children of
Returns:
number of immediate children

countChildren

public static int countChildren(IXml parent,
                                java.lang.String filter)
Counts the number of immediate children in parent with a specific name

Parameters:
parent - The Parent to count children of
Returns:
number of immediate children

create

public static IXml create(java.lang.String name)
Create a new, empty IXml element. This element will have no parent, attributes or children.

Parameters:
name - The name of the IXml element to be created.
Returns:
The newly created IXml object.
Example:
We can create an empty element with:
 XmlUtil.create("boat");  =>  An element with name "boat".

create

public static IXml create(java.lang.String localname,
                          java.lang.String prefix,
                          java.lang.String namespaceURI)
Create a new namespace-aware XML element with the specified localName and optional prefix and namespace URI. See also XmlUtil.create(String name) for creating a namespace unaware elem

Parameters:
localname - - name of the element (no prefix or : allowed)
prefix - - optional prefix qualifier, may be null
namespaceURI - of the namespace to associate this element with.
Returns:
IXml object representing the created parent-less element

createDOM

public static org.w3c.dom.Document createDOM(IXml source)
                                      throws XMLException
Convert an IXml document into a DOM document and return it.

Parameters:
source - The IXml document that is to be converted to DOM.
Returns:
An org.w3c.dom.Document object.
Throws:
XMLException - Any XML exception, possibly wrapping another exception.
Example:
XmlUtil.createDOM(document) =>
 a DOM representation of the IXml document.

createDOM

public static org.w3c.dom.Document createDOM(java.io.Reader source)
                                      throws XMLException
Parses an XML document from the specified Reader into a well formed DOM document (org.w3c.dom.Document).

Parameters:
source - The Reader containing the XML document that is to be parsed.
Returns:
An org.w3c.dom.Document object.
Throws:
XMLException - Any XML exception, possibly wrapping another exception.
Example:
XmlUtil.createDOM(new StringReader("<foo/>")) =>
 an DOM element named "foo".

createDOM

public static org.w3c.dom.Document createDOM(java.lang.String source)
                                      throws XMLException
Parses an XML document from the specified String into a well formed DOM document (org.w3c.dom.Document).

Parameters:
source - The String containing the XML document that is to be parsed.
Returns:
An org.w3c.dom.Document object.
Throws:
XMLException - Any XML exception, possibly wrapping another exception.
Example:
XmlUtil.createDOM("<boat color=\"red\"/>") =>
 an DOM element named "boat" with one attribute named "color".

createObject

public static java.lang.Object createObject(java.lang.Object source,
                                            java.lang.String className)
                                     throws XMLException
Convert an XML document into another representation and return it. If the source is an instance of the specified class name then the source object will be cloned and returned.

Parameters:
source - The Object containing the XML document that is to be converted/cloned.
className - The class name that implements the desired XML object type.
Returns:
An object of the specified class name.
Throws:
XMLException - Any XML exception, possibly wrapping another exception.
Example:
XmlUtil.createObject(document,"org.jdom.Document") =>
 a JDOM representation of the IXml document.

createRawTextElement

public static IXml createRawTextElement(java.lang.String rawText)
Create a section of "raw" text for use in conjunction with writeHtml, to include text with no escaping or quoting of special characters. This can be used, for example, to include some JSP or HTML source which contains characters such as "<" or embedded quotes within an attribute value.

Parameters:
rawText - The raw text to be included.
Returns:
An HTMLContent element which can then be added to a parent element using addChildElement.
Example:
XmlUtil.createRawTextElement("<a href=\"http://<%= getURL() %>\"> ") =>
 creates a special IXml element containing the raw text.  This will be written as-is by writeHtml.

createXml

public static IXml createXml(java.lang.Object source)
                      throws XMLException
Convert an XML document into an IXml document and return it. XML comments are not preserved.

Parameters:
source - The XML document that is to be converted to IXml.
Returns:
An IXml object.
Throws:
XMLException - Any XML exception, possibly wrapping another exception.
Example:
XmlUtil.createXml(document) =>
 an IXml representation of the XML document.

findCommonAncestor

public static IXml findCommonAncestor(IXml node1,
                                      IXml node2)
Finds the closest common ancestor to the two nodes.

Parameters:
node1 -
node2 -
Returns:
closest common ancestor

findElements

public static java.util.List<IXml> findElements(IXml x,
                                                java.lang.String xpath)
Takes an xpath and returns a List of the matching elements. Eg, specify /A/B/C as an xpath and the IXml x will be examined navigating from the root down from A to B to C and a List of all such C elements will be returned (they will still be attached to their B parents). The IXml x passed to this method might have parent elements, ie, we might start out looking at the middle of an XML structure. This is why it's important to specify a "/" on the front of the xpath to denote a search from the root node. Not specifying a "/" will cause the search to start from the current position.

Parameters:
x - the XML to be examined
xpath - the xpath specifying the elements to be returned
Returns:
a List of all matching elements

hasMultipleRoots

public static boolean hasMultipleRoots(java.lang.String xmlStr,
                                       java.lang.String rootName)
This method detects if multiple roots are present in the given XML string. String is expected to represent valid XML.

Parameters:
xmlStr - string to to test for multiple XML root elements
rootName - name of the XML root element
Returns:
true if multiple XML root elements are found or false otherwise.

isContainedWithin

public static boolean isContainedWithin(IXml inner,
                                        IXml outer)
Tests to see if inner (1st arg) is contained anywhere within outer, including recursively

Parameters:
inner - IXml which might be an inner child
outer - IXml which might be the parent or great-parent
Returns:
true if it is contained

lastChildOf

public static IXml lastChildOf(IXml parent)
Finds the last child of an IXml element

Parameters:
parent -
Returns:
the last child, or null if there are no children or if the input is null

parseHtml

public static IXml parseHtml(java.io.Reader in)
                      throws java.io.IOException,
                             com.bowstreet.util.parser.ParserException
Parses an HTML document from the specified Reader into a well formed IXml object.
Note - This method assumes that there is a single parent node, which represents the root of the HTML. The element names needn't be actual HTML element names. Element names will be upper cased.

Parameters:
in - The Reader to the HTML data that is to be parse.
Returns:
An IXml object.
Throws:
java.io.IOException
com.bowstreet.util.parser.ParserException
Example:
StringReader sr = new StringReader("<html><body> hello world </body></html>");
 XmlUtil.parseHtml(sr).getName(); => "HTML"

parseHtml

public static IXml parseHtml(java.lang.String in)
                      throws java.io.IOException,
                             com.bowstreet.util.parser.ParserException
Parses an HTML document from the specified String into a well formed IXml object.
Note - This method assumes that there is a single parent node, which represents the root of the HTML. The element names needn't be actual HTML element names. Element names will be upper cased. Note that in the XHTML standard, HTML names are all in lower case. If you're parsing an XHTML document, use parseXml instead of parseHtml to avoid the upper casing of element names.

Parameters:
in - The string representation of the HTML data that is to be parsed.
Returns:
An IXml object.
Throws:
java.io.IOException
com.bowstreet.util.parser.ParserException
Example:
XmlUtil.parseHtml("<html><body> hello world </body></html>");

parseXml

public static IXml parseXml(java.io.Reader in)
                     throws java.io.IOException
Parses an XML document from the specified Reader into a well formed IXml object. XML comments are not preserved.

Parameters:
in - The Reader for the XML data that is to be parsed.
Returns:
top node of fully parsed XML
Throws:
java.io.IOException
Example:
XmlUtil.parseXml(new StringReader("<snowmobile/>")); => an element
 with name "snowmobile".

parseXml

public static IXml parseXml(java.io.Reader in,
                            boolean validateNamespacePrefixes)
                     throws java.io.IOException
Parses an XML document from the specified Reader into a well formed IXml object. Optionally validates namespace prefixes. XML comments are not preserved. See parseXml for more information.

Parameters:
in - The Reader for the XML data that is to be parsed.
validateNamespacePrefixes - Use false to disable namespace prefix checking.
Returns:
top node of fully parsed XML
Throws:
java.io.IOException

parseXml

public static java.lang.Object parseXml(java.io.Reader source,
                                        java.lang.String className)
                                 throws XMLException
Parses an XML document from the specified Reader into a well formed object of the specified class name.

Parameters:
source - The Reader containing the XML document that is to be parsed.
className - The class name that implements the desired XML object type.
Returns:
An XML object.
Throws:
XMLException - Any XML exception, possibly wrapping another exception.
Example:
XmlUtil.parseXml(new StringReader("<foo/>"), "org.jdom.Document") =>
 an JDOM document containing an element named "foo".

parseXml

public static IXml parseXml(java.lang.String in)
                     throws java.io.IOException
Parses an XML document from the specified String into a well formed IXml object. XML comments are not preserved.

Parameters:
in - The String containing the XML document that is to be parsed.
Returns:
An IXml object.
Throws:
java.io.IOException
Example:
XmlUtil.parseXml("<boat color=\"red\"/>") =>
 an element named "boat" with one attribute named "color".

parseXml

public static java.lang.Object parseXml(java.lang.String source,
                                        java.lang.String className)
                                 throws XMLException
Parses an XML document from the specified String into a well formed object of the specified class name.

Parameters:
source - The String containing the XML document that is to be parsed.
className - The class name that implements the desired XML object type.
Returns:
An XML object.
Throws:
XMLException - Any XML exception, possibly wrapping another exception.
Example:
XmlUtil.parseXml("<boat color=\"red\"/>", "org.jdom.Document") =>
 an JDOM element named "boat" with one attribute named "color".

prettyPrint

public static java.lang.String prettyPrint(IXml xml)

removeAttributes

public static void removeAttributes(IXml node)
Remove all attributes except those that define namespaces

Parameters:
node - node from which to remove all attributes.

safeParseXml

public static IXml safeParseXml(java.lang.String in)
Parses an XML document from the specified String into a well formed IXml object. XML comments are not preserved.

Parameters:
in - The String containing the XML document that is to be parsed.
Returns:
An IXml object or null if there were errors.
Example:
XmlUtil.parseXml("<boat color=\"red\"/>") =>
 an element named "boat" with one attribute named "color".

safeParseXmlFromFile

public static IXml safeParseXmlFromFile(java.lang.String filename)
Parses an XML document from a file. If there are any errors, they are swalled and the result is null.

Parameters:
filename -

toString

public static java.lang.String toString(java.lang.Object source)
                                 throws XMLException
Return the string representation of the specified XML document.

Parameters:
source - The XML document that is to be returned as a string.
Returns:
The string representation of the XML document.
Throws:
XMLException - Any XML exception, possibly wrapping another exception.
Example:
XmlUtil.toString(document) =>
 returns the string representation of the XML document.

writeXml

public static void writeXml(java.lang.Object source,
                            java.io.Writer out)
                     throws XMLException
Write an XML document (IXml, DOM, JDOM) to the specified Writer. Eg:
        Writer writer = new StringWriter();
        XmlUtil.writeXml( document, writer, true);
        return writer.toString();
       

Parameters:
source - The XML document that is to be written.
out - The Writer that the XML document is to be written to.
Throws:
XMLException - Any XML exception, possibly wrapping another exception.

writeXml

public static void writeXml(java.lang.Object source,
                            java.io.Writer out,
                            boolean trimWhitespace)
                     throws XMLException
Same as writeXml, but with option to remove all whitespace from character data and between xml tags, which can be useful when needing to compare several XML documents.

Parameters:
source - The XML document that is to be written.
out - The Writer that the XML document is to be written to.
trimWhitespace - indicates if white space is to be trimmed or not
Throws:
XMLException - Any XML exception, possibly wrapping another exception.


Copyright © 2009 IBM. All Rights Reserved.