//////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Copyright (c) 2018 Saxonica Limited. // This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. // If a copy of the MPL was not distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/. // This Source Code Form is "Incompatible With Secondary Licenses", as defined by the Mozilla Public License, v. 2.0. //////////////////////////////////////////////////////////////////////////////////////////////////////////////////// package net.sf.saxon.dom; import net.sf.saxon.lib.NamespaceConstant; import net.sf.saxon.om.AxisInfo; import net.sf.saxon.om.NamespaceBinding; import net.sf.saxon.om.NodeInfo; import net.sf.saxon.pattern.AnyNodeTest; import net.sf.saxon.pattern.NameTest; import net.sf.saxon.pattern.NodeTest; import net.sf.saxon.tree.iter.AxisIterator; import net.sf.saxon.tree.iter.LookaheadIterator; import net.sf.saxon.tree.util.FastStringBuffer; import net.sf.saxon.tree.util.Navigator; import net.sf.saxon.tree.util.SteppingNavigator; import net.sf.saxon.tree.util.SteppingNode; import net.sf.saxon.tree.wrapper.AbstractNodeWrapper; import net.sf.saxon.tree.wrapper.SiblingCountingNode; import net.sf.saxon.type.Type; import net.sf.saxon.type.UType; import org.jetbrains.annotations.NotNull; import org.w3c.dom.*; import java.util.ArrayList; import java.util.Arrays; /** * A node in the XML parse tree representing an XML element, character content, or attribute. * This is the implementation of the NodeInfo interface used as a wrapper for DOM nodes. *
Because the DOM is not thread-safe even when reading, and because Saxon-EE can spawn multiple * threads that access the same input tree, all methods that invoke DOM methods are synchronized * on the Document object.
*/ @SuppressWarnings({"SynchronizeOnNonFinalField"}) public class DOMNodeWrapper extends AbstractNodeWrapper implements SiblingCountingNode, SteppingNodeNote: a.equals(b) if and only if generateId(a)==generateId(b)
* * @return true if this Node object and the supplied Node object represent the * same node in the tree. */ public boolean equals(Object other) { if (!(other instanceof DOMNodeWrapper)) { return false; } if (docWrapper.domLevel3) { synchronized (docWrapper.docNode) { return node.isSameNode(((DOMNodeWrapper) other).node); } } else { DOMNodeWrapper ow = (DOMNodeWrapper) other; return getNodeKind() == ow.getNodeKind() && equalOrNull(getLocalPart(), ow.getLocalPart()) && // redundant, but gives a quick exit getSiblingPosition() == ow.getSiblingPosition() && getParent().equals(ow.getParent()); } } private boolean equalOrNull(String a, String b) { return a==null ? b==null : a.equals(b); } /** * Determine the relative position of this node and another node, in document order. * The other node will always be in the same document. * * @param other The other node, whose position is to be compared with this node * @return -1 if this node precedes the other node, +1 if it follows the other * node, or 0 if they are the same node. (In this case, isSameNode() will always * return true, and the two nodes will produce the same result for generateId()) */ public int compareOrder(NodeInfo other) { // Use the DOM Level-3 compareDocumentPosition() method if (other instanceof DOMNodeWrapper && docWrapper.domLevel3) { if (equals(other)) { return 0; } try { synchronized (docWrapper.docNode) { short relationship = node.compareDocumentPosition(((DOMNodeWrapper) other).node); if ((relationship & (Node.DOCUMENT_POSITION_PRECEDING | Node.DOCUMENT_POSITION_CONTAINS)) != 0) { return +1; } else if ((relationship & (Node.DOCUMENT_POSITION_FOLLOWING | Node.DOCUMENT_POSITION_CONTAINED_BY)) != 0) { return -1; } } // otherwise use fallback implementation (e.g. nodes in different documents) } catch (DOMException e) { // can happen if nodes are from different DOM implementations. // use fallback implementation } } if (other instanceof SiblingCountingNode) { return Navigator.compareOrder(this, (SiblingCountingNode) other); } else { // it's presumably a Namespace Node return -other.compareOrder(this); } } /** * Get the value of the item as a CharSequence. This is in some cases more efficient than * the version of the method that returns a String. */ public CharSequence getStringValueCS() { synchronized (docWrapper.docNode) { switch (nodeKind) { case Type.DOCUMENT: case Type.ELEMENT: NodeList children1 = node.getChildNodes(); FastStringBuffer sb1 = new FastStringBuffer(16); expandStringValue(children1, sb1); return sb1; case Type.ATTRIBUTE: return emptyIfNull(((Attr) node).getValue()); case Type.TEXT: if (span == 1) { return emptyIfNull(node.getNodeValue()); } else { FastStringBuffer fsb = new FastStringBuffer(FastStringBuffer.C64); Node textNode = node; for (int i = 0; i < span; i++) { fsb.append(emptyIfNull(textNode.getNodeValue())); textNode = textNode.getNextSibling(); } return fsb.condense(); } case Type.COMMENT: case Type.PROCESSING_INSTRUCTION: return emptyIfNull(node.getNodeValue()); default: return ""; } } } /** * Treat a node value of null as an empty string. * * @param s the node value * @return a zero-length string if s is null, otherwise s */ private static String emptyIfNull(String s) { return s == null ? "" : s; } public static void expandStringValue(NodeList list, FastStringBuffer sb) { final int len = list.getLength(); for (int i = 0; i < len; i++) { Node child = list.item(i); switch (child.getNodeType()) { case Node.ELEMENT_NODE: expandStringValue(child.getChildNodes(), sb); break; case Node.COMMENT_NODE: case Node.PROCESSING_INSTRUCTION_NODE: break; case Node.DOCUMENT_TYPE_NODE: break; default: sb.append(emptyIfNull(child.getNodeValue())); break; } } } /** * Get the local part of the name of this node. This is the name after the ":" if any. * * @return the local part of the name. For an unnamed node, returns "". */ public String getLocalPart() { synchronized (docWrapper.docNode) { switch (getNodeKind()) { case Type.ELEMENT: case Type.ATTRIBUTE: return getLocalName(node); case Type.PROCESSING_INSTRUCTION: return node.getNodeName(); default: return ""; } } } /** * Get the local name of a DOM element or attribute node. * * @param node the DOM element or attribute node * @return the local name as defined in XDM */ public static String getLocalName(Node node) { String s = node.getLocalName(); if (s == null) { // true if the node was created using a DOM level 1 method String n = node.getNodeName(); int colon = n.indexOf(':'); if (colon >= 0) { return n.substring(colon + 1); } return n; } else { return s; } } /** * Get the URI part of the name of this node. This is the URI corresponding to the * prefix, or the URI of the default namespace if appropriate. * * @return The URI of the namespace of this node. For an unnamed node, * or for a node with an empty prefix, return an empty * string. */ public String getURI() { synchronized (docWrapper.docNode) { if (nodeKind == Type.ELEMENT) { return getElementURI((Element) node); } else if (nodeKind == Type.ATTRIBUTE) { return getAttributeURI((Attr) node); } return ""; } } private static String getElementURI(Element element) { // The DOM methods getPrefix() and getNamespaceURI() do not always // return the prefix and the URI; they both return null, unless the // prefix and URI have been explicitly set in the node by using DOM // level 2 interfaces. There's no obvious way of deciding whether // an element whose name has no prefix is in the default namespace, // other than searching for a default namespace declaration. So we have to // be prepared to search. // If getPrefix() and getNamespaceURI() are non-null, however, // we can use the values. String uri = element.getNamespaceURI(); if (uri != null) { return uri; } // Otherwise we have to work it out the hard way... String displayName = element.getNodeName(); int colon = displayName.indexOf(':'); String attName = colon < 0 ? "xmlns" : "xmlns:" + displayName.substring(0, colon); if (attName.equals("xmlns:xml")) { return NamespaceConstant.XML; } Node node = element; do { if (((Element) node).hasAttribute(attName)) { return ((Element) node).getAttribute(attName); } node = node.getParentNode(); } while (node != null && node.getNodeType() == Node.ELEMENT_NODE); if (colon < 0) { return ""; } else { throw new IllegalStateException("Undeclared namespace prefix in element name " + displayName + " in DOM input"); } } private static String getAttributeURI(Attr attr) { String uri = attr.getNamespaceURI(); if (uri != null) { return uri; } // Otherwise we have to work it out the hard way... String displayName = attr.getNodeName(); int colon = displayName.indexOf(':'); if (colon < 0) { return ""; } String attName = "xmlns:" + displayName.substring(0, colon); if (attName.equals("xmlns:xml")) { return NamespaceConstant.XML; } Node node = attr.getOwnerElement(); do { if (((Element) node).hasAttribute(attName)) { return ((Element) node).getAttribute(attName); } node = node.getParentNode(); } while (node != null && node.getNodeType() == Node.ELEMENT_NODE); throw new IllegalStateException("Undeclared namespace prefix in attribute name " + displayName + " in DOM input"); } /** * Get the prefix of the name of the node. This is defined only for elements and attributes. * If the node has no prefix, or for other kinds of node, return a zero-length string. * * @return The prefix of the name of the node. */ public String getPrefix() { synchronized (docWrapper.docNode) { int kind = getNodeKind(); if (kind == Type.ELEMENT || kind == Type.ATTRIBUTE) { String name = node.getNodeName(); int colon = name.indexOf(':'); if (colon < 0) { return ""; } else { return name.substring(0, colon); } } return ""; } } /** * Get the display name of this node. For elements and attributes this is [prefix:]localname. * For unnamed nodes, it is an empty string. * * @return The display name of this node. * For a node with no name, return an empty string. */ public String getDisplayName() { switch (nodeKind) { case Type.ELEMENT: case Type.ATTRIBUTE: case Type.PROCESSING_INSTRUCTION: synchronized (docWrapper.docNode) { return node.getNodeName(); } default: return ""; } } /** * Get the NodeInfo object representing the parent of this node */ public DOMNodeWrapper getParent() { if (parent == null) { synchronized (docWrapper.docNode) { switch (getNodeKind()) { case Type.ATTRIBUTE: parent = makeWrapper(((Attr) node).getOwnerElement(), docWrapper); break; default: Node p = node.getParentNode(); if (p == null) { return null; } else { parent = makeWrapper(p, docWrapper); } } } } return parent; } /** * Get the index position of this node among its siblings (starting from 0). * In the case of a text node that maps to several adjacent siblings in the DOM, * the numbering actually refers to the position of the underlying DOM nodes; * thus the sibling position for the text node is that of the first DOM node * to which it relates, and the numbering of subsequent XPath nodes is not necessarily * consecutive. *Despite the name, this method also returns a meaningful result for attribute * nodes; it returns the position of the attribute among the attributes of its * parent element, when they are listed in document order.
*/ public int getSiblingPosition() { if (index == -1) { synchronized (docWrapper.docNode) { switch (nodeKind) { case Type.ELEMENT: case Type.TEXT: case Type.COMMENT: case Type.PROCESSING_INSTRUCTION: int ix = 0; Node start = node; while (true) { start = start.getPreviousSibling(); if (start == null) { index = ix; return ix; } ix++; } case Type.ATTRIBUTE: ix = 0; AxisIterator iter = parent.iterateAxis(AxisInfo.ATTRIBUTE); while (true) { NodeInfo n = iter.next(); if (n == null || Navigator.haveSameName(this, n)) { index = ix; return ix; } ix++; } case Type.NAMESPACE: ix = 0; iter = parent.iterateAxis(AxisInfo.NAMESPACE); while (true) { NodeInfo n = iter.next(); if (n == null || Navigator.haveSameName(this, n)) { index = ix; return ix; } ix++; } default: index = 0; return index; } } } return index; } @Override protected AxisIterator iterateAttributes(NodeTest nodeTest) { AxisIterator iter = new AttributeEnumeration(this); if (nodeTest != AnyNodeTest.getInstance()) { iter = new Navigator.AxisFilter(iter, nodeTest); } return iter; } @Override protected AxisIterator iterateChildren(NodeTest nodeTest) { boolean elementOnly = nodeTest.getUType() == UType.ELEMENT; AxisIterator iter = new Navigator.EmptyTextFilter( new ChildEnumeration(this, true, true, elementOnly)); if (nodeTest != AnyNodeTest.getInstance()) { iter = new Navigator.AxisFilter(iter, nodeTest); } return iter; } @Override protected AxisIterator iterateSiblings(NodeTest nodeTest, boolean forwards) { boolean elementOnly = nodeTest.getUType() == UType.ELEMENT; AxisIterator iter = new Navigator.EmptyTextFilter( new ChildEnumeration(this, false, forwards, elementOnly)); if (nodeTest != AnyNodeTest.getInstance()) { iter = new Navigator.AxisFilter(iter, nodeTest); } return iter; } @Override protected AxisIterator iterateDescendants(NodeTest nodeTest, boolean includeSelf) { return new SteppingNavigator.DescendantAxisIterator(this, includeSelf, nodeTest); } /** * Get the string value of a given attribute of this node * * @param uri the namespace URI of the attribute name. Supply the empty string for an attribute * that is in no namespace * @param local the local part of the attribute name. * @return the attribute value if it exists, or null if it does not exist. Always returns null * if this node is not an element. * @since 9.4 */ public String getAttributeValue(/*@NotNull*/ String uri, /*@NotNull*/ String local) { NameTest test = new NameTest(Type.ATTRIBUTE, uri, local, getNamePool()); AxisIterator iterator = iterateAxis(AxisInfo.ATTRIBUTE, test); NodeInfo attribute = iterator.next(); if (attribute == null) { return null; } else { return attribute.getStringValue(); } } /** * Get the root node - always a document node with this tree implementation * * @return the NodeInfo representing the containing document */ public NodeInfo getRoot() { return docWrapper.getRootNode(); } /** * Determine whether the node has any children. *Note: the result is equivalent to
* getEnumeration(Axis.CHILD, AnyNodeTest.getInstance()).hasNext()
For a node other than an element, the method returns null.
*/ public NamespaceBinding[] getDeclaredNamespaces(NamespaceBinding[] buffer) { synchronized (docWrapper.docNode) { if (node.getNodeType() == Node.ELEMENT_NODE) { if (localNamespaces != null) { return localNamespaces; } Element elem = (Element) node; NamedNodeMap atts = elem.getAttributes(); if (atts == null) { localNamespaces = NamespaceBinding.EMPTY_ARRAY; return NamespaceBinding.EMPTY_ARRAY; } int count = 0; final int attsLen = atts.getLength(); for (int i = 0; i < attsLen; i++) { Attr att = (Attr) atts.item(i); String attName = att.getName(); if (attName.equals("xmlns")) { count++; } else if (attName.startsWith("xmlns:")) { count++; } } if (count == 0) { localNamespaces = NamespaceBinding.EMPTY_ARRAY; return NamespaceBinding.EMPTY_ARRAY; } else { NamespaceBinding[] result = buffer == null || count > buffer.length ? new NamespaceBinding[count] : buffer; int n = 0; for (int i = 0; i < attsLen; i++) { Attr att = (Attr) atts.item(i); String attName = att.getName(); if (attName.equals("xmlns")) { String prefix = ""; String uri = att.getValue(); result[n++] = new NamespaceBinding(prefix, uri); } else if (attName.startsWith("xmlns:")) { String prefix = attName.substring(6); String uri = att.getValue(); result[n++] = new NamespaceBinding(prefix, uri); } } if (count < result.length) { result[count] = null; } localNamespaces = Arrays.copyOf(result, result.length); return result; } } else { return null; } } } /** * Determine whether this node has the is-id property * * @return true if the node is an ID */ public boolean isId() { synchronized (docWrapper.docNode) { return (node instanceof Attr) && ((Attr) node).isId(); } } public DOMNodeWrapper getNextSibling() { synchronized (docWrapper.docNode) { Node currNode = node; for (int i=0; i { private ArrayList