Class XmlDom
- java.lang.Object
-
- com.globalmentor.xml.XmlDom
-
public class XmlDom extends java.lang.Object
Various XML manipulation functions, mostly using the DOM.- Author:
- Garret Wilson
-
-
Field Summary
Fields Modifier and Type Field Description static int
CHARACTER_ENCODING_AUTODETECT_BYTE_COUNT
The number of bytes to use when auto-detecting character encoding.protected static char
REPLACEMENT_CHAR
The character to use to replace any other character.protected static char
REPLACEMENT_FIRST_CHAR
The character to replace the first character if needed.
-
Constructor Summary
Constructors Constructor Description XmlDom()
-
Method Summary
All Methods Static Methods Concrete Methods Modifier and Type Method Description static <N extends org.w3c.dom.Node>
NaddFirst(org.w3c.dom.Node parentNode, N newChildNode)
Adds a node as the first child of the given parent node.static <N extends org.w3c.dom.Node>
NaddLast(org.w3c.dom.Node parentNode, N newChildNode)
Adds a node as the last child of the given parent node.static void
addStyleSheetReference(org.w3c.dom.Document document, java.lang.String href, com.globalmentor.net.ContentType mediaType)
Adds a stylesheet to the XML document using the standard<?xml-stylesheet...>
processing instruction notation.static void
appendClonedAttributeNodesNS(org.w3c.dom.Element destinationElement, org.w3c.dom.Element sourceElement)
Performs a clone on the attributes of the source node and adds them to the destination node.static void
appendClonedChildNodes(org.w3c.dom.Node destinationNode, org.w3c.dom.Node sourceNode, boolean deep)
Performs a clone on the children of the source node and adds them to the destination node.static org.w3c.dom.Element
appendElementNS(org.w3c.dom.Element parentElement, java.lang.String elementNamespaceURI, java.lang.String elementName)
Convenience function to create an element and add it as a child of the given parent element.static org.w3c.dom.Element
appendElementNS(org.w3c.dom.Element parentElement, java.lang.String elementNamespaceURI, java.lang.String elementName, java.lang.String textContent)
Convenience function to create an element, add it as a child of the given parent element, and add optional text as a child of the given element.static void
appendImportedChildNodes(org.w3c.dom.Node destinationNode, org.w3c.dom.Node sourceNode)
Performs a deep import on the children of the source node and adds them to the destination node.static void
appendImportedChildNodes(org.w3c.dom.Node destinationNode, org.w3c.dom.Node sourceNode, boolean deep)
Performs an import on the children of the source node and adds them to the destination node.static org.w3c.dom.Text
appendText(org.w3c.dom.Element element, char textCharacter)
Creates a text node with the specified character and appends it to the specified element.static org.w3c.dom.Text
appendText(org.w3c.dom.Element element, java.lang.String textString)
Creates a text node with the specified text and appends it to the specified element.static java.util.Iterator<org.w3c.dom.Attr>
attributesIterator(org.w3c.dom.Element element)
Retrieves an iterator to the attributes of the given element.static java.util.stream.Stream<org.w3c.dom.Attr>
attributesOf(org.w3c.dom.Element element)
Retrieves the attributes of the given element as a stream of attribute nodes.static java.util.stream.Stream<org.w3c.dom.Element>
childElementsByName(org.w3c.dom.Node parentNode, java.lang.String name)
Returns a stream of direct child elements with a given name, in order.static java.util.stream.Stream<org.w3c.dom.Element>
childElementsByNameNS(org.w3c.dom.Node parentNode, java.lang.String namespaceURI, java.lang.String localName)
Returns a stream of direct child elements with a given namespace URI and local name, in order.static java.util.stream.Stream<org.w3c.dom.Element>
childElementsOf(org.w3c.dom.Element element)
Retrieves the direct child elements of the given element as a stream of elements.static java.util.Iterator<org.w3c.dom.Node>
childNodesIterator(org.w3c.dom.Element element)
Retrieves an iterator to the direct children of the given element.static java.util.stream.Stream<org.w3c.dom.Node>
childNodesOf(org.w3c.dom.Element element)
Retrieves the direct children of the given element as a stream of nodes.static <N extends org.w3c.dom.Node,C extends java.util.Collection<N>>
CcollectNodesByName(org.w3c.dom.Node node, int nodeType, java.lang.Class<N> nodeClass, java.lang.String nodeName, boolean deep, C nodes)
Collects child nodes with a given type and node name.static <N extends org.w3c.dom.Node,C extends java.util.Collection<N>>
CcollectNodesByNameNS(org.w3c.dom.Node node, int nodeType, java.lang.Class<N> nodeClass, java.lang.String namespaceURI, java.lang.String localName, boolean deep, C nodes)
Collects child nodes with a given type, namespace URI, and local name.static org.w3c.dom.Document
createDocument(org.w3c.dom.Element element)
Creates a document wrapped around a copy of the given element.static javax.xml.parsers.DocumentBuilder
createDocumentBuilder()
Creates and returns a document builder without namespace awareness with no validation.static javax.xml.parsers.DocumentBuilder
createDocumentBuilder(boolean namespaceAware)
Creates and returns a document builder, specifying namespace awareness with no validation.static javax.xml.parsers.DocumentBuilder
createDocumentBuilder(boolean namespaceAware, boolean validating)
Creates and returns a document builder, specifying namespace awareness and validation.static javax.xml.parsers.DocumentBuilder
createDocumentBuilder(boolean namespaceAware, boolean validating, org.xml.sax.EntityResolver entityResolver)
Creates and returns a document builder, specifying namespace awareness and validation.static javax.xml.parsers.DocumentBuilder
createDocumentBuilder(boolean namespaceAware, org.xml.sax.EntityResolver entityResolver)
Creates and returns a document builder, specifying namespace awareness with no validation.static javax.xml.parsers.DocumentBuilder
createDocumentBuilder(org.xml.sax.EntityResolver entityResolver)
Creates and returns a document builder without namespace awareness with no validation.static org.w3c.dom.Element
createElementNS(org.w3c.dom.Document document, java.lang.String elementNamespaceURI, java.lang.String elementName, java.lang.String textContent)
Convenience function to create an element and add optional text as a child of the given element.static QualifiedName
createQualifiedName(org.w3c.dom.Node node)
Creates a qualified name object from an XML node.static java.lang.String
createValidContent(java.lang.String string)
Replaces special XML symbols with their escaped versions, (e.g.static java.lang.String
createValidString(java.lang.String string)
Creates a string in which all illegal XML characters are replaced with the space character.static void
declareNamespace(org.w3c.dom.Element declarationElement, java.lang.String prefix, java.lang.String namespaceURI)
Declares a prefix for the given namespace using the appropriatexmlns=
orxmlns:prefix=
attribute declaration for the given element.static void
declareNamespaces(org.w3c.dom.Element declarationElement, com.globalmentor.model.NameValuePair<java.lang.String,java.lang.String>[] prefixNamespacePairs)
Declares prefixes for the given namespaces using the appropriatexmlns=
orxmlns:prefix=
attribute declaration for the given element.static java.nio.charset.Charset
detectXMLCharset(java.io.InputStream inputStream, com.globalmentor.model.ObjectHolder<com.globalmentor.io.ByteOrderMark> bom, com.globalmentor.model.ObjectHolder<java.lang.String> declaredEncodingName)
Attempts to automatically detect the character encoding of a particular input stream that supposedly contains XML data.static void
ensureChildNamespaceDeclarations(org.w3c.dom.Element parentElement)
Checks to ensure that all namespaces for the child elements and their attributes are properly declared using the appropriatexmlns=
orxmlns:prefix=
attribute declaration.protected static void
ensureChildNamespaceDeclarations(org.w3c.dom.Element rootElement, org.w3c.dom.Element parentElement)
Checks to ensure that all namespaces for the child elements and their attributes are properly declared using the appropriatexmlns=
orxmlns:prefix=
attribute declaration.static void
ensureNamespaceDeclaration(org.w3c.dom.Element element, java.lang.String prefix, java.lang.String namespaceURI)
Declares a prefix for the given namespace using the appropriatexmlns=
orxmlns:prefix=
attribute declaration.static void
ensureNamespaceDeclarations(org.w3c.dom.Element element)
Checks to ensure that all namespaces for the element and its attributes are properly declared using the appropriatexmlns=
orxmlns:prefix=
attribute declaration.static void
ensureNamespaceDeclarations(org.w3c.dom.Element element, org.w3c.dom.Element declarationElement, boolean deep)
Checks to ensure that all namespaces for the element and its attributes are properly declared using the appropriatexmlns=
orxmlns:prefix=
attribute declaration.static org.w3c.dom.DocumentFragment
extractChildren(org.w3c.dom.Node node)
Extracts all the child nodes from the given node and places them in a document fragment.static org.w3c.dom.DocumentFragment
extractChildren(org.w3c.dom.Node node, boolean remove)
Extracts all the child nodes from the given node and places them in a document fragment.static org.w3c.dom.DocumentFragment
extractChildren(org.w3c.dom.Node node, int startChildIndex, int endChildIndex)
Extracts the indexed nodes starting atstartChildIndex
up to but not includingendChildIndex
.static org.w3c.dom.DocumentFragment
extractChildren(org.w3c.dom.Node node, int startChildIndex, int endChildIndex, boolean remove)
Extracts the indexed nodes starting atstartChildIndex
up to but not includingendChildIndex
.static org.w3c.dom.DocumentFragment
extractNode(org.w3c.dom.Node node)
Extracts a single node from its parent and places it in a document fragment.static org.w3c.dom.DocumentFragment
extractNode(org.w3c.dom.Node node, boolean remove)
Extracts a single node from its parent and places it in a document fragment.static java.util.Optional<java.lang.String>
findAttribute(org.w3c.dom.Element element, java.lang.String name)
Retrieves an attribute value by name if it exists.static java.util.Optional<java.lang.String>
findAttributeNS(org.w3c.dom.Element element, java.lang.String namespaceURI, java.lang.String localName)
Retrieves an attribute value by local name and namespace URI if it exists.static java.util.Optional<org.w3c.dom.Node>
findFirst(org.w3c.dom.NodeList nodeList)
Retrieves the optional first item of a node list.static java.util.Optional<org.w3c.dom.Node>
findFirstChild(org.w3c.dom.Node parentNode)
Retrieves the optional first child of a node.static java.util.Optional<org.w3c.dom.Element>
findFirstChildElementByNameNS(org.w3c.dom.Node parentNode, java.lang.String namespaceURI, java.lang.String localName)
Returns the first direct child element with a given namespace URI and local name.static java.util.Optional<org.w3c.dom.Element>
findFirstElementByNameNS(org.w3c.dom.NodeList nodeList, java.lang.String namespaceURI, java.lang.String localName)
Returns the first elements with a given namespace URI and local name.static java.util.Optional<org.w3c.dom.Node>
findLastChild(org.w3c.dom.Node parentNode)
Retrieves the optional last child of a node.static java.util.List<org.w3c.dom.Element>
getChildElements(org.w3c.dom.Node node)
Retrieves the nodes contained in child nodes of typeNode.ELEMENT_NODE
.static org.w3c.dom.Node
getChildNode(org.w3c.dom.Node node, int nodeType)
Retrieves the first child node of the specified type.static org.w3c.dom.Node
getChildNodeNot(org.w3c.dom.Node node, int nodeType)
Retrieves the first child node not of the specified type.static com.globalmentor.net.ContentType
getContentTypeForPublicID(java.lang.String publicID)
Determines the content type for the given public ID.protected static java.util.Map<java.lang.String,com.globalmentor.net.ContentType>
getContentTypeMap()
static java.lang.String
getDeclaredNamespaceURI(org.w3c.dom.Element element, java.lang.String prefix, boolean resolve)
Searches the attributes of the given node for a definition of a namespace URI for the given prefix.static java.lang.String
getDefaultRootElementLocalName(com.globalmentor.net.ContentType contentType)
Determines the default root element local name for the given content typestatic java.lang.String
getDefaultSystemID(java.lang.String publicID)
Determines the default system ID for the given public ID.static org.w3c.dom.Document
getDocument(org.w3c.dom.Node node)
Returns the owner document of the given node or, if the node is a document, returns the node itself.static java.util.List<org.w3c.dom.Element>
getElements(java.util.List<org.w3c.dom.Node> nodes)
Returns a list of all elements from the given list of nodes.protected static <N extends org.w3c.dom.Node>
java.util.List<N>getElementsAsType(java.util.List<org.w3c.dom.Node> nodes, short nodeType, java.lang.Class<N> nodeClass)
Returns a list of all nodes of a given type from the given list of nodes.static org.w3c.dom.Node
getFirstNode(org.w3c.dom.Node node, int whatToShow)
Returns the first node in the hierarchy, beginning with the specified node and continuing with a depth-first search, that has a particular node type.static java.lang.String
getNamespaceURI(org.w3c.dom.Element element, java.lang.String prefix, boolean resolve)
Searches the attributes of the given node for a definition of a namespace URI for the given prefix.static java.util.List<org.w3c.dom.Node>
getNodesByName(org.w3c.dom.Node node, int nodeType, java.lang.String nodeName, boolean deep)
Returns a list of child nodes with a given type and node name.static java.util.List<org.w3c.dom.Node>
getNodesByNameNS(org.w3c.dom.Node node, int nodeType, java.lang.String namespaceURI, java.lang.String localName, boolean deep)
Returns a list of child nodes with a given type, namespace URI, and local name.protected static java.util.Map<java.lang.String,java.lang.String>
getRootElementLocalNameMap()
protected static java.util.Map<java.lang.String,java.lang.String>
getSystemIDMap()
static java.lang.String
getText(org.w3c.dom.Node node)
Retrieves the text of the node contained in child nodes of typeNode.TEXT_NODE
, extracting text deeply.static java.lang.String
getText(org.w3c.dom.Node node, boolean deep)
Retrieves the text of the node contained in child nodes of typeNode.TEXT_NODE
.static java.lang.String
getText(org.w3c.dom.Node node, java.util.Set<java.lang.String> blockElementNames)
Retrieves the text of the node contained in child nodes of typeNode.TEXT_NODE
, extracting text deeply.static java.lang.StringBuilder
getText(org.w3c.dom.Node node, java.util.Set<java.lang.String> blockElementNames, boolean deep, java.lang.StringBuilder stringBuilder)
Retrieves the text of the node contained in child nodes of typeNode.Text
.static com.globalmentor.model.NameValuePair<java.lang.String,java.lang.String>[]
getUndeclaredNamespaces(org.w3c.dom.Element element)
Gets the namespace declarations this element needs so that all namespaces for the element and its attributes are properly declared using the appropriatexmlns=
orxmlns:prefix=
attribute declaration.static boolean
hasAncestorElementNS(org.w3c.dom.Element element, java.lang.String ancestorElementNamespaceURI, java.lang.String ancestorElementName)
Determines whether the given element has an ancestor with the given namespace and name.static int
indexOf(org.w3c.dom.NodeList nodeList, org.w3c.dom.Node node)
Returns the index of a given node in a node list.static org.w3c.dom.Element
insertElement(org.w3c.dom.Text textNode, org.w3c.dom.Element element, int startIndex, int endIndex)
Creates and inserts a new element encompassing the text of a given text node.static boolean
isNamespaceDeclared(org.w3c.dom.Element element, java.lang.String prefix, java.lang.String namespaceURI)
Determines if the given namespace is declared using the appropriatexmlns=
orxmlns:prefix=
attribute declaration either on the given element or on any element up the tree.static boolean
isXML(com.globalmentor.net.ContentType contentType)
Determines if the given content type is one representing XML in some form.static boolean
isXMLExternalParsedEntity(com.globalmentor.net.ContentType contentType)
Determines if the given content type is one representing an XML external parsed entity in some form.static java.lang.Iterable<org.w3c.dom.Node>
iterableOf(org.w3c.dom.NamedNodeMap namedNodeMap)
Returns an iterable to iterate through the nodes in a named node map.static java.lang.Iterable<org.w3c.dom.Node>
iterableOf(org.w3c.dom.NodeList nodeList)
Returns an iterable to iterate through the nodes in a node list.static void
mergeAttributesNS(org.w3c.dom.Element targetElement, java.util.stream.Stream<org.w3c.dom.Attr> attributes)
Merges attributes the target element in a namespace-aware manner.static void
mergeAttributesNS(org.w3c.dom.Element targetElement, org.w3c.dom.Element element)
Merges the attributes of some element into the target element in a namespace-aware manner.static org.w3c.dom.Document
parse(java.io.InputStream inputStream)
Creates a document builder and parses an input stream without namespace awareness with no validation.static org.w3c.dom.Document
parse(java.io.InputStream inputStream, boolean namespaceAware)
Creates a document builder and parses an input stream, specifying namespace awareness with no validation.static org.w3c.dom.Document
parse(java.io.InputStream inputStream, boolean namespaceAware, boolean validating)
Creates a document builder and parses an input stream, specifying namespace awareness and validation.static org.w3c.dom.Document
parse(java.io.InputStream inputStream, boolean namespaceAware, boolean validating, org.xml.sax.EntityResolver entityResolver)
Creates a document builder and parses an input stream, specifying namespace awareness and validation.static org.w3c.dom.Document
parse(java.io.InputStream inputStream, boolean namespaceAware, org.xml.sax.EntityResolver entityResolver)
Creates a document builder and parses an input stream, specifying namespace awareness with no validation.static org.w3c.dom.Document
parse(java.io.InputStream inputStream, java.net.URI systemID)
Creates a document builder and parses an input stream without namespace awareness with no validation.static org.w3c.dom.Document
parse(java.io.InputStream inputStream, java.net.URI systemID, boolean namespaceAware)
Creates a document builder and parses an input stream, specifying namespace awareness with no validation.static org.w3c.dom.Document
parse(java.io.InputStream inputStream, java.net.URI systemID, boolean namespaceAware, boolean validating)
Creates a document builder and parses an input stream, specifying namespace awareness and validation.static org.w3c.dom.Document
parse(java.io.InputStream inputStream, java.net.URI systemID, boolean namespaceAware, boolean validating, org.xml.sax.EntityResolver entityResolver)
Creates a document builder and parses an input stream, specifying namespace awareness and validation.static org.w3c.dom.Document
parse(java.io.InputStream inputStream, java.net.URI systemID, boolean namespaceAware, org.xml.sax.EntityResolver entityResolver)
Creates a document builder and parses an input stream, specifying namespace awareness with no validation.static org.w3c.dom.Document
parse(java.io.InputStream inputStream, java.net.URI systemID, org.xml.sax.EntityResolver entityResolver)
Creates a document builder and parses an input stream without namespace awareness with no validation.static org.w3c.dom.Document
parse(java.io.InputStream inputStream, org.xml.sax.EntityResolver entityResolver)
Creates a document builder and parses an input stream without namespace awareness with no validation.static org.w3c.dom.DocumentFragment
parseFragment(java.lang.String fragmentText, javax.xml.parsers.DocumentBuilder documentBuilder, java.lang.String defaultNamespaceURI)
Parses the given text as an XML fragment using the given document builder as a parser.static void
printTree(org.w3c.dom.Document document, java.io.PrintStream printStream)
Prints a tree representation of the document to the standard output.protected static void
printTree(org.w3c.dom.Element element, int tabPos, java.io.PrintStream printStream)
Prints a tree representation of the element to the standard output starting at the specified tab position.static void
printTree(org.w3c.dom.Element element, java.io.PrintStream printStream)
Prints a tree representation of the element to the standard output.protected static void
printTree(org.w3c.dom.Node node, int tabPos, java.io.PrintStream printStream)
Prints a tree representation of the node to the given pring stream starting at the specified tab position.static void
printTree(org.w3c.dom.Node node, java.io.PrintStream printStream)
Prints a tree representation of the node to the given pring stream starting at the specified tab position.static void
pruneChild(org.w3c.dom.Node parentNode, org.w3c.dom.Node childNode)
Removes the specified child node from the parent node, and promoting all the children of the child node to be children of the parent node.static void
removeChildElementsByNameAttribute(org.w3c.dom.Node node, java.lang.String elementName, java.lang.String attributeName, java.lang.String attributeValue)
Removes all child elements with the given name and attribute value.static void
removeChildElementsByNameAttribute(org.w3c.dom.Node node, java.lang.String elementName, java.lang.String attributeName, java.lang.String attributeValue, boolean deep)
Removes all child elements with the given name and attribute value.static <N extends org.w3c.dom.Node>
NremoveChildren(N parentNode)
Removes all children of a node.static void
removeChildren(org.w3c.dom.Node node, int startChildIndex, int endChildIndex)
Removes the indexed nodes starting atstartChildIndex
up to but not includingendChildIndex
.static void
removeChildrenByName(org.w3c.dom.Node node, java.util.Set<java.lang.String> nodeNames)
Removes all named child nodes deeply.static void
removeChildrenByName(org.w3c.dom.Node node, java.util.Set<java.lang.String> nodeNames, boolean deep)
Removes all named child nodes.static org.w3c.dom.Element
replaceDocumentElement(org.w3c.dom.Document document, java.lang.String elementNamespaceURI, java.lang.String elementName)
Convenience function to create an element and use it to replace the document element of the document.static org.w3c.dom.Element
replaceDocumentElementNS(org.w3c.dom.Document document, java.lang.String elementNamespaceURI, java.lang.String elementName, java.lang.String textContent)
Convenience function to create an element, replace the document element of the given document, and add optional text as a child of the given element.static org.w3c.dom.Element
replaceElementNS(org.w3c.dom.Element element, java.lang.String namespaceURI, java.lang.String localName)
Renames an element by creating a new element with the specified name, cloning the original element's children, and replacing the original element with the new, renamed clone.static org.w3c.dom.Text
splitText(org.w3c.dom.Text textNode, int startIndex, int endIndex)
Splits a text node into one, two, or three text nodes and replaces the original text node with the new ones.static java.util.stream.Stream<org.w3c.dom.Node>
streamOf(org.w3c.dom.NamedNodeMap namedNodeMap)
Returns a stream to iterate through the nodes in a named node map.static java.util.stream.Stream<org.w3c.dom.Node>
streamOf(org.w3c.dom.NodeList nodeList)
Returns a stream to iterate through the nodes in a node list.static java.net.URI
toNamespaceURI(java.lang.String namespace)
Creates a namespace URI from the given namespace string.static java.lang.String
toString(org.w3c.dom.Document document)
Converts an XML document to a string.static java.lang.String
toString(org.w3c.dom.Element element)
Converts an XML element to a string.
-
-
-
Field Detail
-
CHARACTER_ENCODING_AUTODETECT_BYTE_COUNT
public static final int CHARACTER_ENCODING_AUTODETECT_BYTE_COUNT
The number of bytes to use when auto-detecting character encoding.
-
REPLACEMENT_FIRST_CHAR
protected static final char REPLACEMENT_FIRST_CHAR
The character to replace the first character if needed.- See Also:
- Constant Field Values
-
REPLACEMENT_CHAR
protected static final char REPLACEMENT_CHAR
The character to use to replace any other character.- See Also:
- Constant Field Values
-
-
Method Detail
-
getSystemIDMap
protected static java.util.Map<java.lang.String,java.lang.String> getSystemIDMap()
- Returns:
- A lazily-created cache of system IDs keyed to public IDs.
-
detectXMLCharset
public static java.nio.charset.Charset detectXMLCharset(java.io.InputStream inputStream, com.globalmentor.model.ObjectHolder<com.globalmentor.io.ByteOrderMark> bom, com.globalmentor.model.ObjectHolder<java.lang.String> declaredEncodingName) throws java.io.IOException, java.nio.charset.UnsupportedCharsetException
Attempts to automatically detect the character encoding of a particular input stream that supposedly contains XML data.- A byte order is attempted to be determined, either by an explicit byte order mark or by the order of the XML declaration start
XML.XML_DECL_START
. If no byte order can be determined,null
is returned. - Based upon the imputed byte order, an explicit encoding is searched for within the XML declaration. If no explicit encoding is found, the imputed byte
order's assumed charset is returned. If a start
XML.XML_DECL_START
but not an endXML.XML_DECL_END
of the XML declaration is found, an exception is thrown. - If an explicit encoding declaration is found, it is returned, unless it is less specific than the imputed byte order. For example, if the imputed byte order is UTF-16BE but the declared encoding is UTF-16, then the charset UTF-16BE is returned.
- If there is no BOM and no XML declaration,
null
is returned; the caller should assume the default XML encoding of UTF-8.
- Parameters:
inputStream
- The stream which supposedly contains XML data; this input stream must support mark/reset.bom
- Receives The actual byte order mark present, if any.declaredEncodingName
- Receives a copy of the explicitly declared name of the character encoding, if any.- Returns:
- The character encoding specified in a byte order mark, the imputed byte order, or the "encoding" attribute; or
null
indicating that no encoding was detecting, allowing the caller to assume UTF-8. - Throws:
java.lang.IllegalArgumentException
- if mark/reset is not supported by the given input stream.java.io.IOException
- Thrown if an I/O error occurred, or the beginning but not the end of an XML declaration was found.java.nio.charset.UnsupportedCharsetException
- If no support for a declared encoding is available in this instance of the Java virtual machine- See Also:
- XML 1.0 (Fifth Edition): F.1 Detection Without External Encoding Information)
- A byte order is attempted to be determined, either by an explicit byte order mark or by the order of the XML declaration start
-
getDefaultSystemID
public static java.lang.String getDefaultSystemID(java.lang.String publicID)
Determines the default system ID for the given public ID.- Parameters:
publicID
- The public ID for which a doctype system ID should be retrieved.- Returns:
- The default doctype system ID corresponding to the given public ID, or
null
if the given public ID is not recognized.
-
getContentTypeMap
protected static java.util.Map<java.lang.String,com.globalmentor.net.ContentType> getContentTypeMap()
- Returns:
- A lazily-created cache of content types keyed to public IDs.
-
getContentTypeForPublicID
public static com.globalmentor.net.ContentType getContentTypeForPublicID(java.lang.String publicID)
Determines the content type for the given public ID.- Parameters:
publicID
- The public ID for which a content type should be retrieved.- Returns:
- The content type corresponding to the given public ID, or
null
if the given public ID is not recognized.
-
getRootElementLocalNameMap
protected static java.util.Map<java.lang.String,java.lang.String> getRootElementLocalNameMap()
- Returns:
- A lazily-created cache of root element local names keyed to content types.
-
getDefaultRootElementLocalName
public static java.lang.String getDefaultRootElementLocalName(com.globalmentor.net.ContentType contentType)
Determines the default root element local name for the given content type- Parameters:
contentType
- The content type for which a root element should be retrieved.- Returns:
- The default root element local name corresponding to the given media type, or
null
if the given content type is not recognized.
-
parse
public static org.w3c.dom.Document parse(java.io.InputStream inputStream) throws java.io.IOException
Creates a document builder and parses an input stream without namespace awareness with no validation. An entity resolver is installed to load requested resources from local resources if possible. This allows quick local lookup of the XHTML DTDs, for example. The Sun JDK 1.5 document builder handles the BOM correctly.Any
SAXException
is converted to anIOException
.- Parameters:
inputStream
- The input stream containing the content to be parsed.- Returns:
- The parsed XML document.
- Throws:
com.globalmentor.model.ConfigurationException
- if a document builder cannot be created which satisfies the configuration requested.java.io.IOException
- If there is an error reading or parsing the information.
-
parse
public static org.w3c.dom.Document parse(java.io.InputStream inputStream, org.xml.sax.EntityResolver entityResolver) throws java.io.IOException
Creates a document builder and parses an input stream without namespace awareness with no validation. The Sun JDK 1.5 document builder handles the BOM correctly.Any
SAXException
is converted to anIOException
.- Parameters:
inputStream
- The input stream containing the content to be parsed.entityResolver
- The strategy to use for resolving entities, ornull
if no entity resolver should be installed.- Returns:
- The parsed XML document.
- Throws:
com.globalmentor.model.ConfigurationException
- if a document builder cannot be created which satisfies the configuration requested.java.io.IOException
- If there is an error reading or parsing the information.
-
parse
public static org.w3c.dom.Document parse(java.io.InputStream inputStream, java.net.URI systemID) throws java.io.IOException
Creates a document builder and parses an input stream without namespace awareness with no validation. An entity resolver is installed to load requested resources from local resources if possible. This allows quick local lookup of the XHTML DTDs, for example. The Sun JDK 1.5 document builder handles the BOM correctly.Any
SAXException
is converted to anIOException
.- Parameters:
inputStream
- The input stream containing the content to be parsed.systemID
- Provide a base for resolving relative URIs.- Returns:
- The parsed XML document.
- Throws:
com.globalmentor.model.ConfigurationException
- if a document builder cannot be created which satisfies the configuration requested.java.io.IOException
- If there is an error reading or parsing the information.
-
parse
public static org.w3c.dom.Document parse(java.io.InputStream inputStream, java.net.URI systemID, org.xml.sax.EntityResolver entityResolver) throws java.io.IOException
Creates a document builder and parses an input stream without namespace awareness with no validation. The Sun JDK 1.5 document builder handles the BOM correctly.Any
SAXException
is converted to anIOException
.- Parameters:
inputStream
- The input stream containing the content to be parsed.systemID
- Provide a base for resolving relative URIs.entityResolver
- The strategy to use for resolving entities, ornull
if no entity resolver should be installed.- Returns:
- The parsed XML document.
- Throws:
com.globalmentor.model.ConfigurationException
- if a document builder cannot be created which satisfies the configuration requested.java.io.IOException
- If there is an error reading or parsing the information.
-
parse
public static org.w3c.dom.Document parse(java.io.InputStream inputStream, boolean namespaceAware) throws java.io.IOException
Creates a document builder and parses an input stream, specifying namespace awareness with no validation. An entity resolver is installed to load requested resources from local resources if possible. This allows quick local lookup of the XHTML DTDs, for example. The Sun JDK 1.5 document builder handles the BOM correctly.Any
SAXException
is converted to anIOException
.- Parameters:
inputStream
- The input stream containing the content to be parsed.namespaceAware
-true
if the parser produced will provide support for XML namespaces, elsefalse
.- Returns:
- The parsed XML document.
- Throws:
com.globalmentor.model.ConfigurationException
- if a document builder cannot be created which satisfies the configuration requested.java.io.IOException
- If there is an error reading or parsing the information.
-
parse
public static org.w3c.dom.Document parse(java.io.InputStream inputStream, boolean namespaceAware, org.xml.sax.EntityResolver entityResolver) throws java.io.IOException
Creates a document builder and parses an input stream, specifying namespace awareness with no validation. The Sun JDK 1.5 document builder handles the BOM correctly.Any
SAXException
is converted to anIOException
.- Parameters:
inputStream
- The input stream containing the content to be parsed.namespaceAware
-true
if the parser produced will provide support for XML namespaces, elsefalse
.entityResolver
- The strategy to use for resolving entities, ornull
if no entity resolver should be installed.- Returns:
- The parsed XML document.
- Throws:
com.globalmentor.model.ConfigurationException
- if a document builder cannot be created which satisfies the configuration requested.java.io.IOException
- If there is an error reading or parsing the information.
-
parse
public static org.w3c.dom.Document parse(java.io.InputStream inputStream, java.net.URI systemID, boolean namespaceAware) throws java.io.IOException
Creates a document builder and parses an input stream, specifying namespace awareness with no validation. An entity resolver is installed to load requested resources from local resources if possible. This allows quick local lookup of the XHTML DTDs, for example. The Sun JDK 1.5 document builder handles the BOM correctly.Any
SAXException
is converted to anIOException
.- Parameters:
inputStream
- The input stream containing the content to be parsed.systemID
- Provide a base for resolving relative URIs.namespaceAware
-true
if the parser produced will provide support for XML namespaces, elsefalse
.- Returns:
- The parsed XML document.
- Throws:
com.globalmentor.model.ConfigurationException
- if a document builder cannot be created which satisfies the configuration requested.java.io.IOException
- If there is an error reading or parsing the information.
-
parse
public static org.w3c.dom.Document parse(java.io.InputStream inputStream, java.net.URI systemID, boolean namespaceAware, org.xml.sax.EntityResolver entityResolver) throws java.io.IOException
Creates a document builder and parses an input stream, specifying namespace awareness with no validation. The Sun JDK 1.5 document builder handles the BOM correctly.Any
SAXException
is converted to anIOException
.- Parameters:
inputStream
- The input stream containing the content to be parsed.systemID
- Provide a base for resolving relative URIs.namespaceAware
-true
if the parser produced will provide support for XML namespaces, elsefalse
.entityResolver
- The strategy to use for resolving entities, ornull
if no entity resolver should be installed.- Returns:
- The parsed XML document.
- Throws:
com.globalmentor.model.ConfigurationException
- if a document builder cannot be created which satisfies the configuration requested.java.io.IOException
- If there is an error reading or parsing the information.
-
parse
public static org.w3c.dom.Document parse(java.io.InputStream inputStream, boolean namespaceAware, boolean validating) throws java.io.IOException
Creates a document builder and parses an input stream, specifying namespace awareness and validation. An entity resolver is installed to load requested resources from local resources if possible. This allows quick local lookup of the XHTML DTDs, for example. The Sun JDK 1.5 document builder handles the BOM correctly.Any
SAXException
is converted to anIOException
.- Parameters:
inputStream
- The input stream containing the content to be parsed.namespaceAware
-true
if the parser produced will provide support for XML namespaces, elsefalse
.validating
-true
if the parser produced will validate documents as they are parsed, elsefalse
.- Returns:
- The parsed XML document.
- Throws:
com.globalmentor.model.ConfigurationException
- if a document builder cannot be created which satisfies the configuration requested.java.io.IOException
- If there is an error reading or parsing the information.
-
parse
public static org.w3c.dom.Document parse(java.io.InputStream inputStream, boolean namespaceAware, boolean validating, org.xml.sax.EntityResolver entityResolver) throws java.io.IOException
Creates a document builder and parses an input stream, specifying namespace awareness and validation. The Sun JDK 1.5 document builder handles the BOM correctly.Any
SAXException
is converted to anIOException
.- Parameters:
inputStream
- The input stream containing the content to be parsed.namespaceAware
-true
if the parser produced will provide support for XML namespaces, elsefalse
.validating
-true
if the parser produced will validate documents as they are parsed, elsefalse
.entityResolver
- The strategy to use for resolving entities, ornull
if no entity resolver should be installed.- Returns:
- The parsed XML document.
- Throws:
com.globalmentor.model.ConfigurationException
- if a document builder cannot be created which satisfies the configuration requested.java.io.IOException
- If there is an error reading or parsing the information.
-
parse
public static org.w3c.dom.Document parse(java.io.InputStream inputStream, java.net.URI systemID, boolean namespaceAware, boolean validating) throws java.io.IOException
Creates a document builder and parses an input stream, specifying namespace awareness and validation. An entity resolver is installed to load requested resources from local resources if possible. This allows quick local lookup of the XHTML DTDs, for example. The Sun JDK 1.5 document builder handles the BOM correctly.Any
SAXException
is converted to anIOException
.- Parameters:
inputStream
- The input stream containing the content to be parsed.systemID
- Provide a base for resolving relative URIs.namespaceAware
-true
if the parser produced will provide support for XML namespaces, elsefalse
.validating
-true
if the parser produced will validate documents as they are parsed, elsefalse
.- Returns:
- The parsed XML document.
- Throws:
com.globalmentor.model.ConfigurationException
- if a document builder cannot be created which satisfies the configuration requested.java.io.IOException
- If there is an error reading or parsing the information.
-
parse
public static org.w3c.dom.Document parse(java.io.InputStream inputStream, java.net.URI systemID, boolean namespaceAware, boolean validating, org.xml.sax.EntityResolver entityResolver) throws java.io.IOException
Creates a document builder and parses an input stream, specifying namespace awareness and validation. The Sun JDK 1.5 document builder handles the BOM correctly.Any
SAXException
is converted to anIOException
.- Parameters:
inputStream
- The input stream containing the content to be parsed.systemID
- Provide a base for resolving relative URIs.namespaceAware
-true
if the parser produced will provide support for XML namespaces, elsefalse
.validating
-true
if the parser produced will validate documents as they are parsed, elsefalse
.entityResolver
- The strategy to use for resolving entities, ornull
if no entity resolver should be installed.- Returns:
- The parsed XML document.
- Throws:
com.globalmentor.model.ConfigurationException
- if a document builder cannot be created which satisfies the configuration requested.java.io.IOException
- If there is an error reading or parsing the information.
-
createDocumentBuilder
public static javax.xml.parsers.DocumentBuilder createDocumentBuilder()
Creates and returns a document builder without namespace awareness with no validation. An entity resolver is installed to load requested resources from local resources if possible. This allows quick local lookup of the XHTML DTDs, for example. The Sun JDK 1.5 document builder handles the BOM correctly.- Returns:
- A new XML document builder.
- Throws:
com.globalmentor.model.ConfigurationException
- if a document builder cannot be created which satisfies the configuration requested.
-
createDocumentBuilder
public static javax.xml.parsers.DocumentBuilder createDocumentBuilder(org.xml.sax.EntityResolver entityResolver)
Creates and returns a document builder without namespace awareness with no validation. The Sun JDK 1.5 document builder handles the BOM correctly.- Parameters:
entityResolver
- The strategy to use for resolving entities, ornull
if no entity resolver should be installed.- Returns:
- A new XML document builder.
- Throws:
com.globalmentor.model.ConfigurationException
- if a document builder cannot be created which satisfies the configuration requested.
-
createDocumentBuilder
public static javax.xml.parsers.DocumentBuilder createDocumentBuilder(boolean namespaceAware)
Creates and returns a document builder, specifying namespace awareness with no validation. An entity resolver is installed to load requested resources from local resources if possible. This allows quick local lookup of the XHTML DTDs, for example. The Sun JDK 1.5 document builder handles the BOM correctly.- Parameters:
namespaceAware
-true
if the parser produced will provide support for XML namespaces, elsefalse
.- Returns:
- A new XML document builder.
- Throws:
com.globalmentor.model.ConfigurationException
- if a document builder cannot be created which satisfies the configuration requested.
-
createDocumentBuilder
public static javax.xml.parsers.DocumentBuilder createDocumentBuilder(boolean namespaceAware, org.xml.sax.EntityResolver entityResolver)
Creates and returns a document builder, specifying namespace awareness with no validation. The Sun JDK 1.5 document builder handles the BOM correctly.- Parameters:
namespaceAware
-true
if the parser produced will provide support for XML namespaces, elsefalse
.entityResolver
- The strategy to use for resolving entities, ornull
if no entity resolver should be installed.- Returns:
- A new XML document builder.
- Throws:
com.globalmentor.model.ConfigurationException
- if a document builder cannot be created which satisfies the configuration requested.
-
createDocumentBuilder
public static javax.xml.parsers.DocumentBuilder createDocumentBuilder(boolean namespaceAware, boolean validating)
Creates and returns a document builder, specifying namespace awareness and validation. An entity resolver is installed to load requested resources from local resources if possible. This allows quick local lookup of the XHTML DTDs, for example. The Sun JDK 1.5 document builder handles the BOM correctly.- Parameters:
namespaceAware
-true
if the parser produced will provide support for XML namespaces, elsefalse
.validating
-true
if the parser produced will validate documents as they are parsed, elsefalse
.- Returns:
- A new XML document builder.
- Throws:
com.globalmentor.model.ConfigurationException
- if a document builder cannot be created which satisfies the configuration requested.
-
createDocumentBuilder
public static javax.xml.parsers.DocumentBuilder createDocumentBuilder(boolean namespaceAware, boolean validating, org.xml.sax.EntityResolver entityResolver)
Creates and returns a document builder, specifying namespace awareness and validation. The Sun JDK 1.5 document builder handles the BOM correctly.- Parameters:
namespaceAware
-true
if the parser produced will provide support for XML namespaces, elsefalse
.validating
-true
if the parser produced will validate documents as they are parsed, elsefalse
.entityResolver
- The strategy to use for resolving entities, ornull
if no entity resolver should be installed.- Returns:
- A new XML document builder.
- Throws:
com.globalmentor.model.ConfigurationException
- if a document builder cannot be created which satisfies the configuration requested.
-
getElements
public static java.util.List<org.w3c.dom.Element> getElements(java.util.List<org.w3c.dom.Node> nodes)
Returns a list of all elements from the given list of nodes.- Parameters:
nodes
- The list of nodes.- Returns:
- A list of all elements in the given list.
- Throws:
java.lang.NullPointerException
- if the given list isnull
.
-
getElementsAsType
protected static <N extends org.w3c.dom.Node> java.util.List<N> getElementsAsType(java.util.List<org.w3c.dom.Node> nodes, short nodeType, java.lang.Class<N> nodeClass)
Returns a list of all nodes of a given type from the given list of nodes.- Type Parameters:
N
- The type of the nodes.- Parameters:
nodes
- The list of nodes.nodeType
- The type of node to retrieve, one of theNode.?_NODE
constants.nodeClass
- The class of the nodes to retrieve.- Returns:
- A list of all nodes of the given type from the given list.
- Throws:
java.lang.NullPointerException
- if the given list isnull
.java.lang.ClassCastException
- if the given node type does not correspond to the given node class.
-
getDocument
public static org.w3c.dom.Document getDocument(org.w3c.dom.Node node)
Returns the owner document of the given node or, if the node is a document, returns the node itself.- Parameters:
node
- The node that may be a document or may have an owner document.- Returns:
- The node owner document (which may be
null
if the node has no owner document) or, if the node is a document, the node itself.
-
getFirstNode
public static org.w3c.dom.Node getFirstNode(org.w3c.dom.Node node, int whatToShow)
Returns the first node in the hierarchy, beginning with the specified node and continuing with a depth-first search, that has a particular node type.- Parameters:
node
- The node which will be checked for nodes, along with its children. The node's owner document should implement theDocumentTraversal
interface.whatToShow
- Which node type(s) to return. See the description ofNodeFilter
for the set of possibleSHOW_
values. These flags can be combined using boolean OR.- Returns:
- The first encountered node in a depth-first (document order) search that matches the filter criteria, or
null
if no matching node exists. - See Also:
NodeIterator
,NodeFilter
-
indexOf
public static int indexOf(org.w3c.dom.NodeList nodeList, org.w3c.dom.Node node)
Returns the index of a given node in a node list.- Parameters:
nodeList
- The node list to search.node
- The node for which an index should be returned.- Returns:
- The index of the node in the given node list, or -1 if the node does not appear in the node list.
-
isXML
public static boolean isXML(com.globalmentor.net.ContentType contentType)
Determines if the given content type is one representing XML in some form.XML media types include:
text/xml
application/xml
application/*+xml
- Parameters:
contentType
- The content type of a resource, ornull
for no content type.- Returns:
true
if the given content type is one of several XML media types.
-
isXMLExternalParsedEntity
public static boolean isXMLExternalParsedEntity(com.globalmentor.net.ContentType contentType)
Determines if the given content type is one representing an XML external parsed entity in some form.XML external parsed entities include:
text/xml-external-parsed-entity
application/xml-external-parsed-entity
text/*+xml-external-parsed-entity
(not formally defined)application/*+xml-external-parsed-entity
(not formally defined)
- Parameters:
contentType
- The content type of a resource, ornull
for no content type.- Returns:
true
if the given content type is one of several XML external parsed entity media types.
-
createValidContent
public static java.lang.String createValidContent(java.lang.String string)
Replaces special XML symbols with their escaped versions, (e.g. replaces '<' with "<") so that the string is valid XML content.- Parameters:
string
- The string to be manipulated.- Returns:
- An XML-friendly string.
-
createValidString
public static java.lang.String createValidString(java.lang.String string)
Creates a string in which all illegal XML characters are replaced with the space character.- Parameters:
string
- The string the characters of which should be checked for XML validity.- Returns:
- A new string with illegal XML characters replaced with spaces, or the original string if no characters were replaced.
-
createQualifiedName
public static QualifiedName createQualifiedName(org.w3c.dom.Node node)
Creates a qualified name object from an XML node.If the node namespace is not a valid URI (e.g. "DAV:"), it will be converted to a valid URI (e.g. "DAV:/") if possible.
- Parameters:
node
- The XML node from which a qualified name is to be created.- Returns:
- A qualified name object representing the given XML node
- Throws:
java.lang.IllegalArgumentException
- if the namespace is notnull
and cannot be converted to a valid URI.- See Also:
toNamespaceURI(String)
-
toNamespaceURI
public static java.net.URI toNamespaceURI(java.lang.String namespace)
Creates a namespace URI from the given namespace string.This method attempts to compensate for XML documents that include a namespace string that is not a true URI, notably the
DAV:
namespace "URI" used by WebDAV. In such a case asDAV:
, the URIDAV:/
would be returned.- Parameters:
namespace
- The namespace string, ornull
if there is no namespace.- Returns:
- A URI representing the namespace, or
null
if no namespace was given. - Throws:
java.lang.IllegalArgumentException
- if the namespace is notnull
and cannot be converted to a valid URI.
-
addStyleSheetReference
public static void addStyleSheetReference(org.w3c.dom.Document document, java.lang.String href, com.globalmentor.net.ContentType mediaType)
Adds a stylesheet to the XML document using the standard<?xml-stylesheet...>
processing instruction notation.- Parameters:
document
- The document to which the stylesheet reference should be added.href
- The reference to the stylesheet.mediaType
- The media type of the stylesheet.
-
appendClonedChildNodes
public static void appendClonedChildNodes(org.w3c.dom.Node destinationNode, org.w3c.dom.Node sourceNode, boolean deep)
Performs a clone on the children of the source node and adds them to the destination node.- Parameters:
destinationNode
- The node that will receive the cloned child nodes.sourceNode
- The node from whence the nodes will be cloned.deep
- Whether each child should be deeply cloned.
-
appendImportedChildNodes
public static void appendImportedChildNodes(org.w3c.dom.Node destinationNode, org.w3c.dom.Node sourceNode)
Performs a deep import on the children of the source node and adds them to the destination node.- Parameters:
destinationNode
- The node that will receive the imported child nodes.sourceNode
- The node from whence the nodes will be imported.
-
appendImportedChildNodes
public static void appendImportedChildNodes(org.w3c.dom.Node destinationNode, org.w3c.dom.Node sourceNode, boolean deep)
Performs an import on the children of the source node and adds them to the destination node.- Parameters:
destinationNode
- The node that will receive the imported child nodes.sourceNode
- The node from whence the nodes will be imported.deep
- Whether each child should be deeply imported.
-
appendClonedAttributeNodesNS
public static void appendClonedAttributeNodesNS(org.w3c.dom.Element destinationElement, org.w3c.dom.Element sourceElement)
Performs a clone on the attributes of the source node and adds them to the destination node. It is assumed that all attributes have been added using namespace aware methods.- Parameters:
destinationElement
- The element that will receive the cloned child nodes.sourceElement
- The element that contains the attributes to be cloned.
-
appendText
public static org.w3c.dom.Text appendText(org.w3c.dom.Element element, char textCharacter)
Creates a text node with the specified character and appends it to the specified element.- Parameters:
element
- The element to which text should be added. This element must have a valid owner document.textCharacter
- The character to add to the element.- Returns:
- The new text node that was created.
-
appendText
public static org.w3c.dom.Text appendText(org.w3c.dom.Element element, java.lang.String textString) throws org.w3c.dom.DOMException
Creates a text node with the specified text and appends it to the specified element.- Parameters:
element
- The element to which text should be added. This element must have a valid owner document.textString
- The text to add to the element.- Returns:
- The new text node that was created.
- Throws:
java.lang.NullPointerException
- if the given element and/or text string isnull
.org.w3c.dom.DOMException
- if there was an error appending the text.
-
replaceDocumentElement
public static org.w3c.dom.Element replaceDocumentElement(org.w3c.dom.Document document, java.lang.String elementNamespaceURI, java.lang.String elementName)
Convenience function to create an element and use it to replace the document element of the document.- Parameters:
document
- The document which will serve as parent of the newly created element.elementNamespaceURI
- The namespace URI of the element to be created.elementName
- The name of the element to create.- Returns:
- The newly created child element.
-
replaceDocumentElementNS
public static org.w3c.dom.Element replaceDocumentElementNS(org.w3c.dom.Document document, java.lang.String elementNamespaceURI, java.lang.String elementName, java.lang.String textContent)
Convenience function to create an element, replace the document element of the given document, and add optional text as a child of the given element. A heading, for instance, might be added usingreplaceDocumentElement(document, XHTML_NAMESPACE_URI, ELEMENT_H2, "My Heading");
.- Parameters:
document
- The document which will serve as parent of the newly created element.elementNamespaceURI
- The namespace URI of the element to be created.elementName
- The name of the element to create.textContent
- The text to add as a child of the created element, ornull
if no text should be added.- Returns:
- The newly created child element.
- Throws:
org.w3c.dom.DOMException
- if there was an error creating the element, appending the text, or replacing the child.
-
appendElementNS
public static org.w3c.dom.Element appendElementNS(org.w3c.dom.Element parentElement, java.lang.String elementNamespaceURI, java.lang.String elementName)
Convenience function to create an element and add it as a child of the given parent element.- Parameters:
parentElement
- The element which will serve as parent of the newly created element. This element must have a valid owner document.elementNamespaceURI
- The namespace URI of the element to be created.elementName
- The name of the element to create.- Returns:
- The newly created child element.
- Throws:
org.w3c.dom.DOMException
- if there was an error creating the element or appending the element to the parent element.
-
appendElementNS
public static org.w3c.dom.Element appendElementNS(org.w3c.dom.Element parentElement, java.lang.String elementNamespaceURI, java.lang.String elementName, java.lang.String textContent)
Convenience function to create an element, add it as a child of the given parent element, and add optional text as a child of the given element. A heading, for instance, might be added usingappendElement(bodyElement, XHTML_NAMESPACE_URI, ELEMENT_H2, "My Heading");
.- Parameters:
parentElement
- The element which will serve as parent of the newly created element. This element must have a valid owner document.elementNamespaceURI
- The namespace URI of the element to be created.elementName
- The name of the element to create.textContent
- The text to add as a child of the created element, ornull
if no text should be added.- Returns:
- The newly created child element.
- Throws:
org.w3c.dom.DOMException
- if there was an error creating the element, appending the text, or appending the element to the parent element.
-
createDocument
public static org.w3c.dom.Document createDocument(org.w3c.dom.Element element)
Creates a document wrapped around a copy of the given element.- Parameters:
element
- The element to become the document element of the new document.- Returns:
- A new document with a clone of the given element as the document element.
-
createElementNS
public static org.w3c.dom.Element createElementNS(org.w3c.dom.Document document, java.lang.String elementNamespaceURI, java.lang.String elementName, java.lang.String textContent) throws org.w3c.dom.DOMException
Convenience function to create an element and add optional text as a child of the given element. A heading, for instance, might be created usingappendElementNS(document, XHTML_NAMESPACE_URI, ELEMENT_H2, "My Heading");
.- Parameters:
document
- The document to be used to create the new element.elementNamespaceURI
- The namespace URI of the element to be created.elementName
- The name of the element to create.textContent
- The text to add as a child of the created element, ornull
if no text should be added.- Returns:
- The newly created child element.
- Throws:
org.w3c.dom.DOMException
- if there was an error creating the element or appending the text.- See Also:
Document.createElementNS(String, String)
,appendText(Element, String)
-
extractNode
public static org.w3c.dom.DocumentFragment extractNode(org.w3c.dom.Node node) throws org.w3c.dom.DOMException
Extracts a single node from its parent and places it in a document fragment. The node is removed from its parent.- Parameters:
node
- The node to be extracted. This node must have a valid parent and owner document.- Returns:
- A new document fragment containing the extracted node.
- Throws:
org.w3c.dom.DOMException
-- NO_MODIFICATION_ALLOWED_ERR: Raised if this node is read-only.
java.lang.IllegalArgumentException
- if the given node has no owner document.java.lang.IllegalArgumentException
- if the given node has no parent node.- See Also:
removeChildren(Node, int, int)
-
extractNode
public static org.w3c.dom.DocumentFragment extractNode(org.w3c.dom.Node node, boolean remove) throws org.w3c.dom.DOMException
Extracts a single node from its parent and places it in a document fragment.- Parameters:
node
- The node to be extracted. This node must have a valid parent and owner document.remove
- Whether the node will be removed from its parent; iffalse
, it will remain the child of its parent.- Returns:
- A new document fragment containing the extracted node.
- Throws:
org.w3c.dom.DOMException
-- NO_MODIFICATION_ALLOWED_ERR: Raised if this node is read-only.
java.lang.IllegalArgumentException
- if the given node has no owner document.java.lang.IllegalArgumentException
- if the given node has no parent node.- See Also:
removeChildren(Node, int, int)
-
extractChildren
public static org.w3c.dom.DocumentFragment extractChildren(org.w3c.dom.Node node) throws org.w3c.dom.DOMException
Extracts all the child nodes from the given node and places them in a document fragment. The children are removed from their parents.- Parameters:
node
- The node from which child nodes should be extracted. This node must have a valid owner document.- Returns:
- A new document fragment containing the extracted children.
- Throws:
org.w3c.dom.DOMException
-- NO_MODIFICATION_ALLOWED_ERR: Raised if this node is read-only.
- See Also:
removeChildren(org.w3c.dom.Node, int, int)
-
extractChildren
public static org.w3c.dom.DocumentFragment extractChildren(org.w3c.dom.Node node, boolean remove) throws org.w3c.dom.DOMException
Extracts all the child nodes from the given node and places them in a document fragment.- Parameters:
node
- The node from which child nodes should be extracted. This node must have a valid owner document.remove
- Whether the nodes will be removed from the parentnode ; iffalse
, they will remain the child of the parent node.- Returns:
- A new document fragment containing the extracted children.
- Throws:
org.w3c.dom.DOMException
-- NO_MODIFICATION_ALLOWED_ERR: Raised if this node is read-only.
- See Also:
removeChildren(org.w3c.dom.Node, int, int)
-
extractChildren
public static org.w3c.dom.DocumentFragment extractChildren(org.w3c.dom.Node node, int startChildIndex, int endChildIndex) throws java.lang.ArrayIndexOutOfBoundsException, org.w3c.dom.DOMException
Extracts the indexed nodes starting atstartChildIndex
up to but not includingendChildIndex
. The children are removed from their parents.- Parameters:
node
- The node from which child nodes should be extracted. This node must have a valid owner document.startChildIndex
- The index of the first child to extract.endChildIndex
- The index directly after the last child to extract. Must be greater thanstartChildIndex
or no action will occur.- Returns:
- A new document fragment containing the extracted children.
- Throws:
java.lang.ArrayIndexOutOfBoundsException
- Thrown if either index is negative, if the start index is greater than or equal to the number of children, or if the ending index is greater than the number of children (unless the ending index is not greater than the starting index). TODO should we throw an exception is startChildIndex>endChildIndex, like String.substring()?java.lang.IllegalArgumentException
- if the given node has no owner document.java.lang.ArrayIndexOutOfBoundsException
- if the given range is invalid for the given node's children.org.w3c.dom.DOMException
-- NO_MODIFICATION_ALLOWED_ERR: Raised if this node is read-only.
- See Also:
removeChildren(Node, int, int)
-
extractChildren
public static org.w3c.dom.DocumentFragment extractChildren(org.w3c.dom.Node node, int startChildIndex, int endChildIndex, boolean remove) throws java.lang.ArrayIndexOutOfBoundsException, org.w3c.dom.DOMException
Extracts the indexed nodes starting atstartChildIndex
up to but not includingendChildIndex
.- Parameters:
node
- The node from which child nodes should be extracted. This node must have a valid owner document.startChildIndex
- The index of the first child to extract.endChildIndex
- The index directly after the last child to extract. Must be greater thanstartChildIndex
or no action will occur.remove
- Whether the nodes will be removed from the parentnode ; iffalse
, they will remain the child of the parent node.- Returns:
- A new document fragment containing the extracted children.
- Throws:
java.lang.ArrayIndexOutOfBoundsException
- Thrown if either index is negative, if the start index is greater than or equal to the number of children, or if the ending index is greater than the number of children (unless the ending index is not greater than the starting index). TODO should we throw an exception is startChildIndex>endChildIndex, like String.substring()?java.lang.IllegalArgumentException
- if the given node has no owner document.java.lang.ArrayIndexOutOfBoundsException
- if the given range is invalid for the given node's children.org.w3c.dom.DOMException
-- NO_MODIFICATION_ALLOWED_ERR: Raised if this node is read-only.
- See Also:
removeChildren(Node, int, int)
-
getChildNode
public static org.w3c.dom.Node getChildNode(org.w3c.dom.Node node, int nodeType)
Retrieves the first child node of the specified type.- Parameters:
node
- The node of which child elements will be examined.nodeType
- The type of node to return.- Returns:
- The first node of the given type, or
null
if there is no such node of the given type.
-
getChildNodeNot
public static org.w3c.dom.Node getChildNodeNot(org.w3c.dom.Node node, int nodeType)
Retrieves the first child node not of the specified type.- Parameters:
node
- The node of which child elements will be examined.nodeType
- The type of node not to return.- Returns:
- The first node not of the given type, or
null
if there is no node not of the given type.
-
getChildElements
public static java.util.List<org.w3c.dom.Element> getChildElements(org.w3c.dom.Node node)
Retrieves the nodes contained in child nodes of typeNode.ELEMENT_NODE
.- Parameters:
node
- The node from which child elements will be returned.- Returns:
- A list with the child nodes.
- See Also:
Node.ELEMENT_NODE
-
getNodesByName
public static java.util.List<org.w3c.dom.Node> getNodesByName(@Nonnull org.w3c.dom.Node node, int nodeType, @Nonnull java.lang.String nodeName, boolean deep)
Returns a list of child nodes with a given type and node name. The special wildcard name "*" returns nodes of all names. Ifdeep
is set totrue
, returns a list of all descendant nodes with a given name, in the order in which they would be encountered in a pre-order traversal of the node tree.- Parameters:
node
- The node the child nodes of which will be searched.nodeType
- The type of nodes to include.nodeName
- The name of the node to match on. The special value "*" matches all nodes.deep
- Whether or not matching child nodes of each matching child node, etc. should be included.- Returns:
- A new list containing all the matching nodes.
-
collectNodesByName
public static <N extends org.w3c.dom.Node,C extends java.util.Collection<N>> C collectNodesByName(@Nonnull org.w3c.dom.Node node, int nodeType, @Nonnull java.lang.Class<N> nodeClass, @Nonnull java.lang.String nodeName, boolean deep, C nodes)
Collects child nodes with a given type and node name. The special wildcard name "*" returns nodes of all names. Ifdeep
is set totrue
, returns a list of all descendant nodes with a given name, in the order in which they would be encountered in a pre-order traversal of the node tree.- Type Parameters:
N
- The type of node to collect.C
- The type of the collection of nodes.- Parameters:
node
- The node the child nodes of which will be searched.nodeType
- The type of nodes to include.nodeClass
- The class representing the type of node to return.nodeName
- The name of the node to match on. The special value "*" matches all nodes.deep
- Whether or not matching child nodes of each matching child node, etc. should be included.nodes
- The collection into which the nodes will be gathered.- Returns:
- The given collection, now containing all the matching nodes.
-
getNodesByNameNS
public static java.util.List<org.w3c.dom.Node> getNodesByNameNS(@Nonnull org.w3c.dom.Node node, int nodeType, @Nullable java.lang.String namespaceURI, @Nonnull java.lang.String localName, boolean deep)
Returns a list of child nodes with a given type, namespace URI, and local name. The special wildcard name "*" returns nodes of all local names. Ifdeep
is set totrue
, returns a list of all descendant nodes with a given name, in the order in which they would be encountered in a pre-order traversal of the node tree.- Parameters:
node
- The node the child nodes of which will be searched.nodeType
- The type of nodes to include.namespaceURI
- The URI of the namespace of nodes to return. The special value "*" matches all namespaces.localName
- The local name of the node to match on. The special value "*" matches all local names.deep
- Whether or not matching child nodes of each matching child node, etc. should be included.- Returns:
- A new list containing all the matching nodes.
-
collectNodesByNameNS
public static <N extends org.w3c.dom.Node,C extends java.util.Collection<N>> C collectNodesByNameNS(@Nonnull org.w3c.dom.Node node, int nodeType, @Nonnull java.lang.Class<N> nodeClass, @Nullable java.lang.String namespaceURI, @Nonnull java.lang.String localName, boolean deep, C nodes)
Collects child nodes with a given type, namespace URI, and local name. The special wildcard name "*" returns nodes of all local names. Ifdeep
is set totrue
, returns a list of all descendant nodes with a given name, in the order in which they would be encountered in a pre-order traversal of the node tree.- Type Parameters:
N
- The type of node to collect.C
- The type of the collection of nodes.- Parameters:
node
- The node the child nodes of which will be searched.nodeType
- The type of nodes to include.nodeClass
- The class representing the type of node to return.namespaceURI
- The URI of the namespace of nodes to return. The special value "*" matches all namespaces.localName
- The local name of the node to match on. The special value "*" matches all local names.deep
- Whether or not matching child nodes of each matching child node, etc. should be included.nodes
- The collection into which the nodes will be gathered.- Returns:
- The given collection, now containing all the matching nodes.
- Throws:
java.lang.ClassCastException
- if one of the nodes of the indicated node type cannot be cast to the indicated node class.
-
getText
public static java.lang.String getText(org.w3c.dom.Node node)
Retrieves the text of the node contained in child nodes of typeNode.TEXT_NODE
, extracting text deeply.- Parameters:
node
- The node from which text will be retrieved.- Returns:
- The data of all
Text
descendant nodes, which may be the empty string. - See Also:
Node.TEXT_NODE
,CharacterData.getData()
-
getText
public static java.lang.String getText(org.w3c.dom.Node node, java.util.Set<java.lang.String> blockElementNames)
Retrieves the text of the node contained in child nodes of typeNode.TEXT_NODE
, extracting text deeply.- Parameters:
node
- The node from which text will be retrieved.blockElementNames
- The names of elements considered "block" elements, which will be separated from other elements using whitespace.- Returns:
- The data of all
Text
descendant nodes, which may be the empty string. - See Also:
Node.TEXT_NODE
,CharacterData.getData()
-
getText
public static java.lang.String getText(org.w3c.dom.Node node, boolean deep)
Retrieves the text of the node contained in child nodes of typeNode.TEXT_NODE
. Ifdeep
is set totrue
the text of all descendant nodes in document (depth-first) order; otherwise, only text of direct children will be returned.- Parameters:
node
- The node from which text will be retrieved.deep
- Whether text of all descendants in document order will be returned.- Returns:
- The data of all
Text
children nodes, which may be the empty string. - See Also:
Node.TEXT_NODE
,CharacterData.getData()
-
getText
public static java.lang.StringBuilder getText(org.w3c.dom.Node node, java.util.Set<java.lang.String> blockElementNames, boolean deep, java.lang.StringBuilder stringBuilder)
Retrieves the text of the node contained in child nodes of typeNode.Text
. Ifdeep
is set totrue
the text of all descendant nodes in document (depth-first) order; otherwise, only text of direct children will be returned.- Parameters:
node
- The node from which text will be retrieved.blockElementNames
- The names of elements considered "block" elements, which will be separated from other elements using whitespace.deep
- Whether text of all descendants in document order will be returned.stringBuilder
- The buffer to which text will be added.- Returns:
- The given string builder.
- See Also:
Node.TEXT_NODE
,CharacterData.getData()
-
hasAncestorElementNS
public static boolean hasAncestorElementNS(org.w3c.dom.Element element, java.lang.String ancestorElementNamespaceURI, java.lang.String ancestorElementName)
Determines whether the given element has an ancestor with the given namespace and name.- Parameters:
element
- The element the ancestors of which to check.ancestorElementNamespaceURI
- The namespace URI of the ancestor element to check for.ancestorElementName
- The name of the ancestor element to check for.- Returns:
true
if an ancestor element with the given namespace URI and name was found.
-
insertElement
public static org.w3c.dom.Element insertElement(org.w3c.dom.Text textNode, org.w3c.dom.Element element, int startIndex, int endIndex) throws org.w3c.dom.DOMException
Creates and inserts a new element encompassing the text of a given text node.- Parameters:
textNode
- The text node to split into a new element.element
- The element to insert.startIndex
- The index of the first character to include in the element.endIndex
- The index immediately after the last character to include in the element.- Returns:
- The inserted element.
- Throws:
org.w3c.dom.DOMException
-- INDEX_SIZE_ERR: Raised if the specified offset is negative or greater than the number of 16-bit units in
data
. - NO_MODIFICATION_ALLOWED_ERR: Raised if this node is read-only.
- INDEX_SIZE_ERR: Raised if the specified offset is negative or greater than the number of 16-bit units in
-
splitText
public static org.w3c.dom.Text splitText(org.w3c.dom.Text textNode, int startIndex, int endIndex) throws org.w3c.dom.DOMException
Splits a text node into one, two, or three text nodes and replaces the original text node with the new ones.- Parameters:
textNode
- The text node to split.startIndex
- The index of the first character to be split.endIndex
- The index immediately after the last character to split.- Returns:
- The new text node that contains the text selected by the start and ending indexes.
- Throws:
org.w3c.dom.DOMException
-- INDEX_SIZE_ERR: Raised if the specified offset is negative or greater than the number of 16-bit units in
data
. - NO_MODIFICATION_ALLOWED_ERR: Raised if this node is read-only.
- INDEX_SIZE_ERR: Raised if the specified offset is negative or greater than the number of 16-bit units in
-
pruneChild
public static void pruneChild(org.w3c.dom.Node parentNode, org.w3c.dom.Node childNode)
Removes the specified child node from the parent node, and promoting all the children of the child node to be children of the parent node.- Parameters:
parentNode
- The parent of the node to remove.childNode
- The node to remove, promoting its children in the process. //TODO list exceptions
-
removeChildren
public static void removeChildren(org.w3c.dom.Node node, int startChildIndex, int endChildIndex) throws java.lang.ArrayIndexOutOfBoundsException, org.w3c.dom.DOMException
Removes the indexed nodes starting atstartChildIndex
up to but not includingendChildIndex
.- Parameters:
node
- The node from which child nodes should be removed.startChildIndex
- The index of the first child to remove.endChildIndex
- The index directly after the last child to remove. Must be greater thanstartChildIndex
or no action will occur.- Throws:
java.lang.ArrayIndexOutOfBoundsException
- Thrown if either index is negative, if the start index is greater than or equal to the number of children, or if the ending index is greater than the number of children. TODO should we throw an exception is startChildIndex>endChildIndex, like String.substring()?org.w3c.dom.DOMException
-- NO_MODIFICATION_ALLOWED_ERR: Raised if this node is read-only.
-
removeChildrenByName
public static void removeChildrenByName(org.w3c.dom.Node node, java.util.Set<java.lang.String> nodeNames)
Removes all named child nodes deeply.- Parameters:
node
- The node the named children of which should be removed.nodeNames
- The names of the nodes to remove.- Throws:
java.lang.NullPointerException
- if the given node and/or node names isnull
.
-
removeChildrenByName
public static void removeChildrenByName(org.w3c.dom.Node node, java.util.Set<java.lang.String> nodeNames, boolean deep)
Removes all named child nodes.- Parameters:
node
- The node the named children of which should be removed.nodeNames
- The names of the nodes to remove.deep
- If all descendants should be examined.- Throws:
java.lang.NullPointerException
- if the given node and/or node names isnull
.
-
removeChildElementsByNameAttribute
public static void removeChildElementsByNameAttribute(org.w3c.dom.Node node, java.lang.String elementName, java.lang.String attributeName, java.lang.String attributeValue)
Removes all child elements with the given name and attribute value.- Parameters:
node
- The node the named child elements of which should be removed.elementName
- The names of the elements to remove.attributeName
- The name of the attribute to check.attributeValue
- The value of the attribute indicating removal.
-
removeChildElementsByNameAttribute
public static void removeChildElementsByNameAttribute(org.w3c.dom.Node node, java.lang.String elementName, java.lang.String attributeName, java.lang.String attributeValue, boolean deep)
Removes all child elements with the given name and attribute value.- Parameters:
node
- The node the named child elements of which should be removed.elementName
- The names of the elements to remove.attributeName
- The name of the attribute to check.attributeValue
- The value of the attribute indicating removal.deep
- If all descendants should be examined.
-
replaceElementNS
public static org.w3c.dom.Element replaceElementNS(org.w3c.dom.Element element, java.lang.String namespaceURI, java.lang.String localName)
Renames an element by creating a new element with the specified name, cloning the original element's children, and replacing the original element with the new, renamed clone. While this method's purpose is renaming, because of DOM restrictions it must remove the element and replace it with a new one, which is reflected by the method's name.- Parameters:
element
- The element to rename.namespaceURI
- The new element namespace.localName
- The new element local name.- Returns:
- The new element with the specified name which replaced the old element. //TODO list exceptions
-
printTree
public static void printTree(org.w3c.dom.Document document, java.io.PrintStream printStream)
Prints a tree representation of the document to the standard output.- Parameters:
document
- The document to print.printStream
- The stream (e.g.System.out
) to use for printing the tree.
-
printTree
public static void printTree(org.w3c.dom.Element element, java.io.PrintStream printStream)
Prints a tree representation of the element to the standard output.- Parameters:
element
- The element to print.printStream
- The stream (e.g.System.out
) to use for printing the tree.
-
printTree
protected static void printTree(org.w3c.dom.Element element, int tabPos, java.io.PrintStream printStream)
Prints a tree representation of the element to the standard output starting at the specified tab position.- Parameters:
element
- The element to print.tabPos
- The zero-based tab position to which to align.printStream
- The stream (e.g.System.out
) to use for printing the tree.
-
printTree
public static void printTree(org.w3c.dom.Node node, java.io.PrintStream printStream)
Prints a tree representation of the node to the given pring stream starting at the specified tab position.- Parameters:
node
- The node to print.printStream
- The stream (e.g.System.out
) to use for printing the tree.
-
printTree
protected static void printTree(org.w3c.dom.Node node, int tabPos, java.io.PrintStream printStream)
Prints a tree representation of the node to the given pring stream starting at the specified tab position.- Parameters:
node
- The node to print.tabPos
- The zero-based tab position to which to align.printStream
- The stream (e.g.System.out
) to use for printing the tree.
-
toString
public static java.lang.String toString(org.w3c.dom.Document document)
Converts an XML document to a string. If an error occurs converting the document to a string, the normal object string will be returned.- Parameters:
document
- The XML document to convert.- Returns:
- A string representation of the XML document.
-
toString
public static java.lang.String toString(org.w3c.dom.Element element)
Converts an XML element to a string. If an error occurs converting the element to a string, the normal object string will be returned.- Parameters:
element
- The XML element to convert.- Returns:
- A string representation of the XML element.
-
getNamespaceURI
public static java.lang.String getNamespaceURI(org.w3c.dom.Element element, java.lang.String prefix, boolean resolve)
Searches the attributes of the given node for a definition of a namespace URI for the given prefix. If the prefix is not defined for the given element, its ancestors are searched if requested. If the prefix is not defined anywhere up the hieararchy,null
is returned. If the prefix is defined, it is returned logically: a blank declared namespace will returnnull
.- Parameters:
element
- The element which should be searched for a namespace definition, along with its ancestors.prefix
- The namespace prefix for which a definition should be found, ornull
for a default attribute.resolve
- Whether the entire tree hierarchy should be searched.- Returns:
- The defined namespace URI for the given prefix, or
null
if none is defined.
-
getDeclaredNamespaceURI
public static java.lang.String getDeclaredNamespaceURI(org.w3c.dom.Element element, java.lang.String prefix, boolean resolve)
Searches the attributes of the given node for a definition of a namespace URI for the given prefix. If the prefix is not defined for the given element, its ancestors are searched if requested. If the prefix is not defined anywhere up the hieararchy,null
is returned. If the prefix is defined, it is returned literally: a blank declared namespace will return the empty string. This allows differentiation between a declared empty namespace and no declared namespace.- Parameters:
element
- The element which should be searched for a namespace definition, along with its ancestors.prefix
- The namespace prefix for which a definition should be found, ornull
for a default attribute.resolve
- Whether the entire tree hierarchy should be searched.- Returns:
- The defined namespace URI for the given prefix, or
null
if none is defined.
-
ensureNamespaceDeclarations
public static void ensureNamespaceDeclarations(org.w3c.dom.Element element)
Checks to ensure that all namespaces for the element and its attributes are properly declared using the appropriatexmlns=
orxmlns:prefix=
attribute declaration.- Parameters:
element
- The element the namespace of which to declare.
-
ensureNamespaceDeclarations
public static void ensureNamespaceDeclarations(org.w3c.dom.Element element, org.w3c.dom.Element declarationElement, boolean deep)
Checks to ensure that all namespaces for the element and its attributes are properly declared using the appropriatexmlns=
orxmlns:prefix=
attribute declaration. The children of this element are optionally checked.- Parameters:
element
- The element the namespace of which to declare.declarationElement
- The element on which to declare missing namespaces, ornull
if namespaces should always be declared on the element on which they are found missing.deep
- Whether all children and their descendants are also recursively checked for namespace declarations.
-
ensureChildNamespaceDeclarations
public static void ensureChildNamespaceDeclarations(org.w3c.dom.Element parentElement)
Checks to ensure that all namespaces for the child elements and their attributes are properly declared using the appropriatexmlns=
orxmlns:prefix=
attribute declaration. If a child element does not have a necessary namespace declaration, the declaration is added to the same parent element all the way down the hierarchy if there are no conflicts. If there is a conflict, the namespace is added to the child element itself.This method is useful for adding namespace attributes to the top level of a fragment that contains unknown content that preferably should be lef undisturbed.
- Parameters:
parentElement
- The element to which all child namespaces will be added if there are no conflicts.
-
ensureChildNamespaceDeclarations
protected static void ensureChildNamespaceDeclarations(org.w3c.dom.Element rootElement, org.w3c.dom.Element parentElement)
Checks to ensure that all namespaces for the child elements and their attributes are properly declared using the appropriatexmlns=
orxmlns:prefix=
attribute declaration. If a child element does not have a necessary namespace declaration, the declaration is added to the same parent element all the way down the hierarchy if there are no conflicts. If there is a conflict, the namespace is added to the child element itself.This method is useful for adding namespace attributes to the top level of a fragment that contains unknown content that preferably should be lef undisturbed.
- Parameters:
rootElement
- The element to which all child namespaces will be added if there are no conflicts.parentElement
- The element the children of which are currently being checked.
-
getUndeclaredNamespaces
public static com.globalmentor.model.NameValuePair<java.lang.String,java.lang.String>[] getUndeclaredNamespaces(org.w3c.dom.Element element)
Gets the namespace declarations this element needs so that all namespaces for the element and its attributes are properly declared using the appropriatexmlns=
orxmlns:prefix=
attribute declaration. The children of this element are optionally checked.- Parameters:
element
- The element for which namespace declarations should be checked.- Returns:
- An array of name/value pairs. The name of each is the the prefix to declare, or
null
if no prefix is used. The value of each is the URI string of the namespace being defined, ornull
if no namespace is used.
-
ensureNamespaceDeclaration
public static void ensureNamespaceDeclaration(org.w3c.dom.Element element, java.lang.String prefix, java.lang.String namespaceURI)
Declares a prefix for the given namespace using the appropriatexmlns=
orxmlns:prefix=
attribute declaration.It is assumed that the namespace is used at the level of the given element. If the namespace prefix is already declared somewhere up the tree, and that prefix is assigned to the same namespace, no action occurs.
- Parameters:
element
- The element for which the namespace should be declared.prefix
- The prefix to declare, ornull
if no prefix is used.namespaceURI
- The namespace being defined, ornull
if no namespace is used.
-
isNamespaceDeclared
public static boolean isNamespaceDeclared(org.w3c.dom.Element element, java.lang.String prefix, java.lang.String namespaceURI)
Determines if the given namespace is declared using the appropriatexmlns=
orxmlns:prefix=
attribute declaration either on the given element or on any element up the tree.The "xmlns" and "xml" prefixes and namespaces always result in
true
being returned, because they never need to be declared.- Parameters:
element
- The element for which the namespace should be declared.prefix
- The prefix to declare, ornull
if no prefix is used.namespaceURI
- The namespace being defined, ornull
if no namespace is used.- Returns:
true
if the namespace is sufficiently declared, either on the given element or somewhere up the element hierarchy.
-
declareNamespaces
public static void declareNamespaces(org.w3c.dom.Element declarationElement, com.globalmentor.model.NameValuePair<java.lang.String,java.lang.String>[] prefixNamespacePairs)
Declares prefixes for the given namespaces using the appropriatexmlns=
orxmlns:prefix=
attribute declaration for the given element.- Parameters:
declarationElement
- The element on which the namespaces should be declared.prefixNamespacePairs
- An array of name/value pairs. The name of each is the the prefix to declare, ornull
if no prefix is used. The value of each is the URI string of the namespace being defined, ornull
if no namespace is used.
-
declareNamespace
public static void declareNamespace(org.w3c.dom.Element declarationElement, java.lang.String prefix, java.lang.String namespaceURI)
Declares a prefix for the given namespace using the appropriatexmlns=
orxmlns:prefix=
attribute declaration for the given element.- Parameters:
declarationElement
- The element on which the namespace should be declared.prefix
- The prefix to declare, ornull
if no prefix is used.namespaceURI
- The namespace being defined, ornull
if no namespace is used.
-
parseFragment
public static org.w3c.dom.DocumentFragment parseFragment(java.lang.String fragmentText, javax.xml.parsers.DocumentBuilder documentBuilder, java.lang.String defaultNamespaceURI) throws org.xml.sax.SAXException
Parses the given text as an XML fragment using the given document builder as a parser.- Parameters:
fragmentText
- The text of the XML fragment.documentBuilder
- The document builder to use to parse the fragment.defaultNamespaceURI
- The default namespace URI of the fragment, ornull
if there is no default namespace- Returns:
- A document fragment containing the parsed contents of the given fragment text.
- Throws:
org.xml.sax.SAXException
- if there was an error parsing the fragment.
-
addFirst
public static <N extends org.w3c.dom.Node> N addFirst(@Nonnull org.w3c.dom.Node parentNode, @Nonnull N newChildNode)
Adds a node as the first child of the given parent node.- API Note:
- This functionality is analogous to
Deque.addFirst(Object)
. - Type Parameters:
N
- The type of child node to add.- Parameters:
parentNode
- The parent node to which the node should be added.newChildNode
- The node to add at the parent node.- Returns:
- The added child.
- See Also:
addLast(Node, Node)
-
addLast
public static <N extends org.w3c.dom.Node> N addLast(@Nonnull org.w3c.dom.Node parentNode, @Nonnull N newChildNode)
Adds a node as the last child of the given parent node.- API Note:
- This method functions identically to
Node.appendChild(Node)
, but conveniently returns the added child node as the correct type., This functionality is analogous toDeque.addLast(Object)
. - Type Parameters:
N
- The type of child node to add.- Parameters:
parentNode
- The parent node to which the node should be added.newChildNode
- The node to add at the parent node.- Returns:
- The added child.
- See Also:
Node.appendChild(Node)
,addFirst(Node, Node)
-
childElementsByName
public static java.util.stream.Stream<org.w3c.dom.Element> childElementsByName(@Nonnull org.w3c.dom.Node parentNode, @Nonnull java.lang.String name)
Returns a stream of direct child elements with a given name, in order.- Parameters:
parentNode
- The node the child nodes of which will be searched.name
- The name of the node to match on.- Returns:
- A stream containing all the matching child elements.
-
childElementsByNameNS
public static java.util.stream.Stream<org.w3c.dom.Element> childElementsByNameNS(@Nonnull org.w3c.dom.Node parentNode, @Nullable java.lang.String namespaceURI, @Nonnull java.lang.String localName)
Returns a stream of direct child elements with a given namespace URI and local name, in order.- Parameters:
parentNode
- The node the child nodes of which will be searched.namespaceURI
- The URI of the namespace of nodes to return.localName
- The local name of the node to match on.- Returns:
- A stream containing all the matching child elements.
-
findFirstChild
public static java.util.Optional<org.w3c.dom.Node> findFirstChild(@Nonnull org.w3c.dom.Node parentNode)
Retrieves the optional first child of a node.- API Note:
- This method provides no new functionality, but is useful because it is often desirable just to get the first child as an
Optional
. - Parameters:
parentNode
- The parent node to examine.- Returns:
- The first child node of the parent node, if any.
- See Also:
Node.getFirstChild()
-
findFirstChildElementByNameNS
public static java.util.Optional<org.w3c.dom.Element> findFirstChildElementByNameNS(@Nonnull org.w3c.dom.Node parentNode, @Nullable java.lang.String namespaceURI, @Nonnull java.lang.String localName)
Returns the first direct child element with a given namespace URI and local name.- Parameters:
parentNode
- The node the child nodes of which will be searched.namespaceURI
- The URI of the namespace of nodes to return.localName
- The local name of the node to match on.- Returns:
- The first matching element, if any.
-
findLastChild
public static java.util.Optional<org.w3c.dom.Node> findLastChild(@Nonnull org.w3c.dom.Node parentNode)
Retrieves the optional last child of a node.- API Note:
- This method provides no new functionality, but is useful because it is often desirable just to get the last child as an
Optional
. - Parameters:
parentNode
- The parent node to examine.- Returns:
- The last child node of the parent node, if any.
- See Also:
Node.getLastChild()
-
removeChildren
public static <N extends org.w3c.dom.Node> N removeChildren(@Nonnull N parentNode) throws org.w3c.dom.DOMException
Removes all children of a node.- Implementation Note:
- Implementation inspired by Stack Overflow post.
- Type Parameters:
N
- The type of parent node.- Parameters:
parentNode
- The node from which child nodes should be removed.- Returns:
- The given node.
- Throws:
org.w3c.dom.DOMException
-- NO_MODIFICATION_ALLOWED_ERR: Raised if this node is read-only.
-
iterableOf
public static java.lang.Iterable<org.w3c.dom.Node> iterableOf(@Nonnull org.w3c.dom.NamedNodeMap namedNodeMap)
Returns an iterable to iterate through the nodes in a named node map. The returned iterator fails fast if it detects that the named node map was modified during iteration.- Parameters:
namedNodeMap
- The named node map to iterate through.- Returns:
- An iterable for iterating the nodes in the named node map.
-
streamOf
public static java.util.stream.Stream<org.w3c.dom.Node> streamOf(@Nonnull org.w3c.dom.NamedNodeMap namedNodeMap)
Returns a stream to iterate through the nodes in a named node map. The returned stream fails fast if it detects that the named node map was modified during iteration.- Parameters:
namedNodeMap
- The named node map to iterate through.- Returns:
- A stream for iterating the nodes in the named node map.
-
findFirst
public static java.util.Optional<org.w3c.dom.Node> findFirst(@Nonnull org.w3c.dom.NodeList nodeList)
Retrieves the optional first item of a node list.- API Note:
- This method provides no new functionality, but is useful because it is often desirable just to get the first node, if any, in a returned list.
- Parameters:
nodeList
- The node list to examine.- Returns:
- The first node in the list, which will not be present if the list is empty.
-
findFirstElementByNameNS
public static java.util.Optional<org.w3c.dom.Element> findFirstElementByNameNS(@Nonnull org.w3c.dom.NodeList nodeList, @Nullable java.lang.String namespaceURI, @Nonnull java.lang.String localName)
Returns the first elements with a given namespace URI and local name.- Parameters:
nodeList
- The nodes to be searched.namespaceURI
- The URI of the namespace of nodes to return.localName
- The local name of the node to match on.- Returns:
- The first matching element, if any.
-
iterableOf
public static java.lang.Iterable<org.w3c.dom.Node> iterableOf(@Nonnull org.w3c.dom.NodeList nodeList)
Returns an iterable to iterate through the nodes in a node list. The returned iterator fails fast if it detects that the node list was modified during iteration.- Parameters:
nodeList
- The node list to iterate through.- Returns:
- An iterable for iterating the nodes in the node list.
-
streamOf
public static java.util.stream.Stream<org.w3c.dom.Node> streamOf(@Nonnull org.w3c.dom.NodeList nodeList)
Returns a stream to iterate through the nodes in a node list. The returned stream fails fast if it detects that the node list was modified during iteration.- Parameters:
nodeList
- The node list to iterate through.- Returns:
- A stream for iterating the nodes in the node list.
-
childNodesIterator
public static java.util.Iterator<org.w3c.dom.Node> childNodesIterator(@Nonnull org.w3c.dom.Element element)
Retrieves an iterator to the direct children of the given element. The iterator supports removal.- Implementation Specification:
- The returned iterator supports
Iterator.remove()
. - Parameters:
element
- The element for which child nodes should be returned.- Returns:
- An iterator of the element's child nodes.
-
childNodesOf
public static java.util.stream.Stream<org.w3c.dom.Node> childNodesOf(@Nonnull org.w3c.dom.Element element)
Retrieves the direct children of the given element as a stream of nodes.- Parameters:
element
- The element for which child nodes should be returned.- Returns:
- A stream of the element's child nodes.
-
childElementsOf
public static java.util.stream.Stream<org.w3c.dom.Element> childElementsOf(@Nonnull org.w3c.dom.Element element)
Retrieves the direct child elements of the given element as a stream of elements.- Implementation Specification:
- This is a convenience method that delegates to
childNodesOf(Element)
and filters out all nodes except those of node typeNode.ELEMENT_NODE
. - Parameters:
element
- The element for which child elements should be returned.- Returns:
- A stream of the element's direct child elements.
- See Also:
Node.ELEMENT_NODE
-
attributesIterator
public static java.util.Iterator<org.w3c.dom.Attr> attributesIterator(@Nonnull org.w3c.dom.Element element)
Retrieves an iterator to the attributes of the given element.- Implementation Specification:
- The returned iterator supports
Iterator.remove()
. - Parameters:
element
- The element for which attributes should be returned.- Returns:
- An iterator of the element's attributes.
-
attributesOf
public static java.util.stream.Stream<org.w3c.dom.Attr> attributesOf(@Nonnull org.w3c.dom.Element element)
Retrieves the attributes of the given element as a stream of attribute nodes.- Parameters:
element
- The element for which attributes should be returned.- Returns:
- A stream of the element's attributes.
-
findAttribute
public static java.util.Optional<java.lang.String> findAttribute(@Nonnull org.w3c.dom.Element element, @Nonnull java.lang.String name)
Retrieves an attribute value by name if it exists.- Implementation Note:
- This method functions similarly to
Element.getAttribute(String)
, except that the attribute is guaranteed to exist to prevent ambiguity with the empty string, which earlier versions of the DOM were supposed to return if the attribute did not exist. - Parameters:
element
- The element for which an attribute should be returned.name
- The name of the attribute to retrieve.- Returns:
- The attribute value as a string, which will not be present if the attribute does not have a specified or default value.
-
findAttributeNS
public static java.util.Optional<java.lang.String> findAttributeNS(@Nonnull org.w3c.dom.Element element, @Nullable java.lang.String namespaceURI, @Nonnull java.lang.String localName) throws org.w3c.dom.DOMException
Retrieves an attribute value by local name and namespace URI if it exists.- Implementation Note:
- This method functions similarly to
Element.getAttributeNS(String, String)
, except that the attribute is guaranteed to exist to prevent ambiguity with the empty string, which earlier versions of the DOM were supposed to return if the attribute did not exist. - Parameters:
element
- The element for which an attribute should be returned.namespaceURI
- The namespace URI of the attribute to retrieve.localName
- The local name of the attribute to retrieve.- Returns:
- The attribute value as a string, which will not be present if the attribute does not have a specified or default value.
- Throws:
org.w3c.dom.DOMException
-- NOT_SUPPORTED_ERR: May be raised if the implementation does not support the feature
"XML"
and the language exposed through the Document does not support XML Namespaces (such as [HTML 4.01]).
- NOT_SUPPORTED_ERR: May be raised if the implementation does not support the feature
- See Also:
Element.hasAttributeNS(String, String)
,Element.getAttributeNS(String, String)
-
mergeAttributesNS
public static void mergeAttributesNS(@Nonnull org.w3c.dom.Element targetElement, @Nonnull org.w3c.dom.Element element)
Merges the attributes of some element into the target element in a namespace-aware manner. If an attribute exists in the other element, its value will replace the value, if any, in the target element. Any target element attributes not present in the other element will remain.- Implementation Specification:
- This implementation delegates to
mergeAttributesNS(Element, Stream)
. - Implementation Note:
- Any attribute value set or updated by this method will use the namespace prefix of the other element, which means that even if the target element contains an attribute with the same value, its namespace prefix may change. Although the namespace URI is guaranteed to be correct, no checks are performed to ensure that the target document has defined the new namespace prefix, if any.
- Parameters:
targetElement
- The element into which the attributes will be merged.element
- The element the attributes of which will be merged into the target element.- See Also:
Element.setAttributeNS(String, String, String)
-
mergeAttributesNS
public static void mergeAttributesNS(@Nonnull org.w3c.dom.Element targetElement, @Nonnull java.util.stream.Stream<org.w3c.dom.Attr> attributes)
Merges attributes the target element in a namespace-aware manner. Any attribute's value will replace the value, if any, in the target element. Any target element attributes not present in the other attributes will remain.- Implementation Note:
- Any attribute value set or updated by this method will use the namespace prefix of the other attributes, which means that even if the target element contains an attribute with the same value, its namespace prefix may change. Although the namespace URI is guaranteed to be correct, no checks are performed to ensure that the target document has defined the new namespace prefix, if any.
- Parameters:
targetElement
- The element into which the attributes will be merged.attributes
- The attributes to be merged into the target element.- See Also:
Element.setAttributeNS(String, String, String)
-
-