com.cleancode.xml
Class DocumentPlus

java.lang.Object
  extended by org.apache.xerces.dom.NodeImpl
      extended by org.apache.xerces.dom.ChildNode
          extended by org.apache.xerces.dom.ParentNode
              extended by org.apache.xerces.dom.CoreDocumentImpl
                  extended by org.apache.xerces.dom.DocumentImpl
                      extended by com.cleancode.xml.DocumentPlus
All Implemented Interfaces:
Serializable, Cloneable, Document, org.w3c.dom.events.DocumentEvent, org.w3c.dom.events.EventTarget, Node, NodeList, org.w3c.dom.ranges.DocumentRange, org.w3c.dom.traversal.DocumentTraversal

public class DocumentPlus
extends org.apache.xerces.dom.DocumentImpl

Adds several convenience methods to a standard org.w3c.dom.Document object.

  import ...xml.DocumentPlus;
  doc = new DocumentPlus();
  node = doc.copyNode("<x>...</x>");
  node = doc.copyNode(foreignNode);
  node = createNode("<abc>hello <i>world</i></abc>");
  doc.appendTextChild(node, "title", "of mice and men");

  node = doc.getSelectedElementByTagName("projectSpec", "myKey", "p2");
  node = doc.getSelectedElementByTagName("projectSpec", "/abc/def");
  node = doc.getSelectedElementByTagName("/abc/def/projectSpec");
  username = doc.getSelectedNodeText("username");
  nodelist = doc.getElementsByTagName("/abc/def/item");
  nodelist = doc.getElementsByTagName("item", "/abc/def");
  String s = doc.getNodeText(node);
  node = doc.getSelectedChild(node, "unique-item");
  String s = doc.getSelectedChildText(node, "unique-item");
 

Since:
CleanCode 0.9
Version:
$Revision: 380 $
Author:
Michael Sorens
See Also:
Serialized Form

Nested Class Summary
static class DocumentPlus.Test
          A standalone test class for a sanity check.
 
Field Summary
static String VERSION
          Current version of this class.
 
Fields inherited from class org.apache.xerces.dom.DocumentImpl
eventListeners, iterators, mutationEvents, ranges
 
Fields inherited from class org.apache.xerces.dom.CoreDocumentImpl
actualEncoding, allowGrammarAccess, changes, docElement, docType, encoding, errorChecking, fDocumentURI, identifiers, standalone, userData, version, xmlVersionChanged
 
Fields inherited from class org.apache.xerces.dom.ParentNode
firstChild, fNodeListCache, ownerDocument
 
Fields inherited from class org.apache.xerces.dom.ChildNode
nextSibling, previousSibling
 
Fields inherited from class org.apache.xerces.dom.NodeImpl
DOCUMENT_POSITION_CONTAINS, DOCUMENT_POSITION_DISCONNECTED, DOCUMENT_POSITION_FOLLOWING, DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC, DOCUMENT_POSITION_IS_CONTAINED, DOCUMENT_POSITION_PRECEDING, ELEMENT_DEFINITION_NODE, FIRSTCHILD, flags, HASSTRING, ID, IGNORABLEWS, NORMALIZED, OWNED, ownerNode, READONLY, SPECIFIED, SYNCCHILDREN, SYNCDATA, TREE_POSITION_ANCESTOR, TREE_POSITION_DESCENDANT, TREE_POSITION_DISCONNECTED, TREE_POSITION_EQUIVALENT, TREE_POSITION_FOLLOWING, TREE_POSITION_PRECEDING, TREE_POSITION_SAME_NODE
 
Fields inherited from interface org.w3c.dom.Node
ATTRIBUTE_NODE, CDATA_SECTION_NODE, COMMENT_NODE, DOCUMENT_FRAGMENT_NODE, DOCUMENT_NODE, DOCUMENT_POSITION_CONTAINED_BY, DOCUMENT_POSITION_CONTAINS, DOCUMENT_POSITION_DISCONNECTED, DOCUMENT_POSITION_FOLLOWING, DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC, DOCUMENT_POSITION_PRECEDING, DOCUMENT_TYPE_NODE, ELEMENT_NODE, ENTITY_NODE, ENTITY_REFERENCE_NODE, NOTATION_NODE, PROCESSING_INSTRUCTION_NODE, TEXT_NODE
 
Constructor Summary
DocumentPlus()
          Create a new DocumentPlus object adding the methods contained herein.
DocumentPlus(Document docToWrap)
          Create a new DocumentPlus object based on the supplied Document, adding the methods contained herein.
 
Method Summary
static Node appendTextChild(Document doc, Node parent, String nodeName, String nodeValue)
          Adds an element named nodeName containing only the text nodeValue to the provided parent node in the given Document..
 Node appendTextChild(Node parent, String nodeName, String nodeValue)
          Adds an element named nodeName containing only the text nodeValue to the provided parent node.
 Element createElement(String tagName)
          A pass-through to the original Document object.
 Node createNode(String elemText)
          Create a node tree from a string.
 String dumpXml()
          Displays the xml contained in the DocumentPlus object.
 String dumpXml(Node node)
          Displays the xml contained in the specified Node (or Element).
 NodeList getElementsByTagName(String tag)
          Extends the base method to allow not just a tagName but also a path argument.
 NodeList getElementsByTagName(String tagName, String path)
          A variation of the standard method, this version constrains the returned NodeList to contain only nodes on the specified path, rather than nodes from anywhere in the tree.
 String getNodeText(Node node)
          Returns the text of the specified node and its descendants.
 Node getSelectedChild(Node node, String tagName)
          Finds a direct child node of a particular node.
 String getSelectedChildText(Node node, String tagName)
          Finds the contents of a direct child node of a particular node.
 Element getSelectedElementByTagName(String tag)
          Collects the output of the standard getElementsByTagName method, then filters it to return the single node in the specified path in the XML.
 Element getSelectedElementByTagName(String tagName, String path)
          Collects the output of the standard getElementsByTagName method, then filters it to return the single node in the specified path and tagName in the XML.
 Element getSelectedElementByTagName(String tagName, String keyField, String keyValue)
          Collects the output of the standard getElementsByTagName method, then filters it to return the single node with the specified keyValue.
 String getSelectedNodeText(String tagName)
          Returns text of first node matching tagName.
 
Methods inherited from class org.apache.xerces.dom.DocumentImpl
addEventListener, cloneNode, copyEventListeners, createEvent, createNodeIterator, createNodeIterator, createRange, createTreeWalker, createTreeWalker, dispatchAggregateEvents, dispatchAggregateEvents, dispatchEvent, dispatchEventToSubtree, dispatchingEventToSubtree, getEventListeners, getImplementation, removeEventListener, saveEnclosingAttr, setEventListeners
 
Methods inherited from class org.apache.xerces.dom.CoreDocumentImpl
abort, adoptNode, changed, changes, checkDOMNSErr, checkNamespaceWF, checkQName, clearIdentifiers, clone, cloneNode, createAttribute, createAttributeNS, createAttributeNS, createCDATASection, createComment, createDocumentFragment, createDocumentType, createElementDefinition, createElementNS, createElementNS, createEntity, createEntityReference, createNotation, createProcessingInstruction, createTextNode, getAsync, getBaseURI, getDoctype, getDocumentElement, getDocumentURI, getDomConfig, getElementById, getElementsByTagNameNS, getEncoding, getErrorChecking, getFeature, getIdentifier, getIdentifiers, getInputEncoding, getNodeName, getNodeNumber, getNodeNumber, getNodeType, getOwnerDocument, getStandalone, getStrictErrorChecking, getTextContent, getUserData, getUserData, getUserDataRecord, getVersion, getXmlEncoding, getXmlStandalone, getXmlVersion, importNode, insertBefore, isKidOK, isValidQName, isXMLName, load, loadXML, normalizeDocument, putIdentifier, removeChild, removeIdentifier, renameNode, replaceChild, saveXML, setAsync, setDocumentURI, setEncoding, setErrorChecking, setInputEncoding, setStandalone, setStrictErrorChecking, setTextContent, setUserData, setUserData, setVersion, setXmlEncoding, setXmlStandalone, setXmlVersion, undeferChildren
 
Methods inherited from class org.apache.xerces.dom.ParentNode
getChildNodes, getChildNodesUnoptimized, getFirstChild, getLastChild, getLength, hasChildNodes, isEqualNode, item, normalize, setReadOnly, synchronizeChildren
 
Methods inherited from class org.apache.xerces.dom.ChildNode
getNextSibling, getParentNode, getPreviousSibling
 
Methods inherited from class org.apache.xerces.dom.NodeImpl
addEventListener, appendChild, compareDocumentPosition, compareTreePosition, dispatchEvent, getAttributes, getContainer, getLocalName, getNamespaceURI, getNodeValue, getPrefix, getReadOnly, getUserData, getUserData, getUserDataRecord, hasAttributes, isDefaultNamespace, isSameNode, isSupported, lookupNamespaceURI, lookupPrefix, needsSyncChildren, removeEventListener, setNodeValue, setPrefix, setUserData, setUserData, synchronizeData, toString
 
Methods inherited from class java.lang.Object
equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait
 
Methods inherited from interface org.w3c.dom.Node
appendChild, compareDocumentPosition, getAttributes, getChildNodes, getFirstChild, getLastChild, getLocalName, getNamespaceURI, getNextSibling, getNodeValue, getParentNode, getPrefix, getPreviousSibling, getUserData, hasAttributes, hasChildNodes, isDefaultNamespace, isEqualNode, isSameNode, isSupported, lookupNamespaceURI, lookupPrefix, normalize, setNodeValue, setPrefix, setUserData
 

Field Detail

VERSION

public static final String VERSION
Current version of this class.

Constructor Detail

DocumentPlus

public DocumentPlus(Document docToWrap)
Create a new DocumentPlus object based on the supplied Document, adding the methods contained herein.

WARNING! You may use Document methods on the returned object only for creation; any retrieval ones (e.g. getElementsByTagNameNS) not explicitly overridden in this class will not work since I have not figured out how to fold the Document into this DocumentPlus object. If you use the no-argument form of this constructor, then everything will work fine since the internal Document object will be involved from the time of object creation.

Parameters:
docToWrap - Document object to wrap

DocumentPlus

public DocumentPlus()
Create a new DocumentPlus object adding the methods contained herein.

Method Detail

createElement

public Element createElement(String tagName)
A pass-through to the original Document object.

Specified by:
createElement in interface Document
Overrides:
createElement in class org.apache.xerces.dom.CoreDocumentImpl
Parameters:
tagName - name of Element's tag to be created
Returns:
Element for specified tagName

dumpXml

public String dumpXml()
Displays the xml contained in the DocumentPlus object. This string will begin with a standard XML processing instruction specifying the xml version.

Returns:
textual representation of the XML.

dumpXml

public String dumpXml(Node node)
Displays the xml contained in the specified Node (or Element). This string will not include a standard XML processing instruction since it represents an XML fragment.

Parameters:
node - Node to dump.
Returns:
textual representation of the XML.

createNode

public Node createNode(String elemText)
                throws ParserConfigurationException,
                       SAXException,
                       IOException
Create a node tree from a string. This is a simple way to convert an XML fragment as a string into a DOM subtree.

Parameters:
elemText - textual representation of an XML element.
Returns:
a new Node representation of elemText in current document's context.
Throws:
ParserConfigurationException - on parser problem
SAXException - on SAX problem
IOException - on file problem

getElementsByTagName

public NodeList getElementsByTagName(String tagName,
                                     String path)
A variation of the standard method, this version constrains the returned NodeList to contain only nodes on the specified path, rather than nodes from anywhere in the tree.

Parameters:
tagName - a tagName
path - a path at which to constrain the tagName
Returns:
a list of matching nodes only at the end of the specified path.
See Also:
getElementsByTagName(String)

getElementsByTagName

public NodeList getElementsByTagName(String tag)
Extends the base method to allow not just a tagName but also a path argument. A tagName argument returns the usual NodeList, containing matching nodes from anywhere in the tree. A path argument constrains the NodeList to contain only nodes on the specified path. Examples:
getElementsByTagName("abc") will find <abc> nodes from anywhere in the document.
getElementsByTagName("/top/items/abc") will find only those <abc> nodes that are direct descendants of /top/items.

Specified by:
getElementsByTagName in interface Document
Overrides:
getElementsByTagName in class org.apache.xerces.dom.CoreDocumentImpl
Parameters:
tag - a tag name or a simple path ending in a tag name
Returns:
if passed a tagName, a list of matching nodes from anywhere in the document; if passed a path, a list of matching nodes only at that specific branch.
See Also:
getElementsByTagName(String,String)

getSelectedElementByTagName

public Element getSelectedElementByTagName(String tagName,
                                           String keyField,
                                           String keyValue)
Collects the output of the standard getElementsByTagName method, then filters it to return the single node with the specified keyValue. The unique key may be any attribute of an element; the keyField identifies which attribute to examine.

Example: With this XML...
 
  <root>
    <projectSpec myKey="p1">
      <count>25</count>
      <owner>fred</owner>
    </projectSpec>
    <projectSpec mode="25" myKey="p3">
      <count/>
      <owner>sarah</owner>
    </projectSpec>
    <projectSpec myKey="p2" other="green">
      <count>25</count>
      <owner>wizard</owner>
    </projectSpec>
  </root>
 
and this code...
   elem=xmlDoc.getSelectedElementByTagName("projectSpec", "myKey", "p2");
 
...then elem contains the <projectSpec> subtree where myKey equals "p2". This provides a mechanism for getting one data subtree among a number of similar nodes.

Parameters:
tagName - XML tag name
keyField - XML attribute name within the targetNodeName
keyValue - value to match in the keyField
Returns:
Selected element or null if no matching element

getSelectedElementByTagName

public Element getSelectedElementByTagName(String tagName,
                                           String path)
Collects the output of the standard getElementsByTagName method, then filters it to return the single node in the specified path and tagName in the XML.

Example: With this XML...
  <topElement>
    <L1><L2><L3>
      <bottom>potogold</bottom>
    </L3></L2></L1>
  </topElement>
 
and any one of these lines of code...
   elem=Doc.getSelectedElementByTagName("bottom","/topElement/L1/L2/L3");
   elem=Doc.getSelectedElementByTagName("bottom","topElement/L1/L2/L3");
   elem=Doc.getSelectedElementByTagName("bottom","L1/L2/L3");
   elem=Doc.getSelectedElementByTagName("bottom","L3");
   elem=Doc.getSelectedElementByTagName("bottom","");
 
...then elem contains the node <bottom>. Note that you may use an absolute (rooted) path or a relative path, as shown in the examples above. If you use an absolute path, you're assured of finding a unique node. In either case, there may be more than one node that could match; the first one found in the XML traversal is returned.

Parameters:
tagName - XML element tag name
path - Xpath expression for a path to an element
Returns:
Selected element or null if no matching element
See Also:
getSelectedElementByTagName(String)

getSelectedElementByTagName

public Element getSelectedElementByTagName(String tag)
Collects the output of the standard getElementsByTagName method, then filters it to return the single node in the specified path in the XML.

Example: With this XML...
  <topElement>
    <L1><L2><L3>
      <bottom>potogold</bottom>
    </L3></L2></L1>
  </topElement>
 
and any one of these lines of code...
   elem=Doc.getSelectedElementByTagName("/topElement/L1/L2/L3/bottom");
   elem=Doc.getSelectedElementByTagName("topElement/L1/L2/L3/bottom");
   elem=Doc.getSelectedElementByTagName("L1/L2/L3/bottom");
   elem=Doc.getSelectedElementByTagName("L3/bottom");
   elem=Doc.getSelectedElementByTagName("bottom");
 
...then elem contains the node <bottom>. Note that you may use an absolute (rooted) path or a relative path, as shown in the examples above. If you use an absolute path, you're assured of finding a unique node. In either case, there may be more than one node that could match; the first one found in the XML traversal is returned.

Parameters:
tag - Xpath expression for an element (not an attribute)
Returns:
Selected element or null if no matching element
See Also:
getSelectedElementByTagName(String,String)

getSelectedChild

public Node getSelectedChild(Node node,
                             String tagName)
Finds a direct child node of a particular node.

Parameters:
node - Node from which to find a child
tagName - name of child element to find
Returns:
child Node

getSelectedChildText

public String getSelectedChildText(Node node,
                                   String tagName)
Finds the contents of a direct child node of a particular node.

Parameters:
node - Node from which to find a child
tagName - name of child element to find
Returns:
text of the selected child Node

getSelectedNodeText

public String getSelectedNodeText(String tagName)
Returns text of first node matching tagName. This routine assumes the node contains only text and is unique. Typically useful in reading a data or configuration file.

Example: With this XML...
  <root>
    <param1>25</param1>
    <param2>fred</param2>
    <param3>true</param3>
  </root>
 
and this code...
  System.out.println(xmlDoc.getSelectedNodeText("param3"));
 
...then the output will be the string "true".

Parameters:
tagName - XML tag name
Returns:
text of node or empty string if no matching nodes.

getNodeText

public String getNodeText(Node node)
Returns the text of the specified node and its descendants. All text nodes within the hierarchy of Elements rooted at the specified node are concatenated.

Parameters:
node - Node from which to extract text
Returns:
text of node and its descendants

appendTextChild

public Node appendTextChild(Node parent,
                            String nodeName,
                            String nodeValue)
Adds an element named nodeName containing only the text nodeValue to the provided parent node.

Parameters:
parent - node object
nodeName - name of child node to add to <parent>
nodeValue - text content of node nodeName
Returns:
input node <parent> (just as a convenience)

appendTextChild

public static Node appendTextChild(Document doc,
                                   Node parent,
                                   String nodeName,
                                   String nodeValue)
Adds an element named nodeName containing only the text nodeValue to the provided parent node in the given Document..

Parameters:
doc - target Document object
parent - node object
nodeName - name of child node to add to <parent>
nodeValue - text content of node nodeName
Returns:
input node <parent> (just as a convenience)


CleanCode Java Libraries Copyright © 2001-2012 Michael Sorens - Revised 2012.12.10 Get CleanCode at SourceForge.net. Fast, secure and Free Open Source software downloads