Java Code Examples for org.w3c.dom.Node#getParentNode()

The following examples show how to use org.w3c.dom.Node#getParentNode() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: TreeWalkerImpl.java    From openjdk-jdk8u with GNU General Public License v2.0 6 votes vote down vote up
/** Internal function.
 *  Return the parent Node, from the input node
 *  after applying filter, whatToshow.
 *  The current node is not consulted or set.
 */
Node getParentNode(Node node) {

    if (node == null || node == fRoot) return null;

    Node newNode = node.getParentNode();
    if (newNode == null)  return null;

    int accept = acceptNode(newNode);

    if (accept == NodeFilter.FILTER_ACCEPT)
        return newNode;
    else
    //if (accept == NodeFilter.SKIP_NODE) // and REJECT too.
    {
        return getParentNode(newNode);
    }


}
 
Example 2
Source File: ElementImpl.java    From Bytecoder with Apache License 2.0 6 votes vote down vote up
private Node getNextLogicalSibling(Node n) {
    Node next = n.getNextSibling();
    // If "n" has no following sibling and its parent is an entity reference node we
    // need to continue the search through the following siblings of the entity
    // reference as these are logically siblings of the given node.
    if (next == null) {
        Node parent = n.getParentNode();
        while (parent != null && parent.getNodeType() == Node.ENTITY_REFERENCE_NODE) {
            next = parent.getNextSibling();
            if (next != null) {
                break;
            }
            parent = parent.getParentNode();
        }
    }
    return next;
}
 
Example 3
Source File: NippinOptionalDeflateTransformer.java    From freehealth-connector with GNU Affero General Public License v3.0 6 votes vote down vote up
private XMLSignatureInput processElement(XMLSignatureInput input, OutputStream os) throws TechnicalConnectorException, IOException {
   Node el = input.getSubNode();
   if (input.getSubNode().getNodeType() == 3) {
      el = el.getParentNode();
   }

   StringBuilder sb = new StringBuilder();
   this.traverseElement((Element)el, sb);
   if (os == null) {
      byte[] decodedBytes = ConnectorIOUtils.decompress(ConnectorIOUtils.toBytes(sb.toString(), Charset.UTF_8));
      return new XMLSignatureInput(decodedBytes);
   } else {
      os.write(ConnectorIOUtils.decompress(ConnectorIOUtils.toBytes(sb.toString(), Charset.UTF_8)));
      XMLSignatureInput output = new XMLSignatureInput((byte[])null);
      output.setOutputStream(os);
      return output;
   }
}
 
Example 4
Source File: XSDocumentInfo.java    From openjdk-jdk8u with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Initialize namespace support by collecting all of the namespace
 * declarations in the root's ancestors. This is necessary to
 * support schemas fragments, i.e. schemas embedded in other
 * documents. See,
 *
 * https://jaxp.dev.java.net/issues/show_bug.cgi?id=43
 *
 * Requires the DOM to be created with namespace support enabled.
 */
private void initNamespaceSupport(Element schemaRoot) {
    fNamespaceSupport = new SchemaNamespaceSupport();
    fNamespaceSupport.reset();

    Node parent = schemaRoot.getParentNode();
    while (parent != null && parent.getNodeType() == Node.ELEMENT_NODE
            && !parent.getNodeName().equals("DOCUMENT_NODE"))
    {
        Element eparent = (Element) parent;
        NamedNodeMap map = eparent.getAttributes();
        int length = (map != null) ? map.getLength() : 0;
        for (int i = 0; i < length; i++) {
            Attr attr = (Attr) map.item(i);
            String uri = attr.getNamespaceURI();

            // Check if attribute is an ns decl -- requires ns support
            if (uri != null && uri.equals("http://www.w3.org/2000/xmlns/")) {
                String prefix = attr.getLocalName().intern();
                if (prefix == "xmlns") prefix = "";
                // Declare prefix if not set -- moving upwards
                if (fNamespaceSupport.getURI(prefix) == null) {
                    fNamespaceSupport.declarePrefix(prefix,
                            attr.getValue().intern());
                }
            }
        }
        parent = parent.getParentNode();
    }
}
 
Example 5
Source File: XSDocumentInfo.java    From openjdk-8-source with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Initialize namespace support by collecting all of the namespace
 * declarations in the root's ancestors. This is necessary to
 * support schemas fragments, i.e. schemas embedded in other
 * documents. See,
 *
 * https://jaxp.dev.java.net/issues/show_bug.cgi?id=43
 *
 * Requires the DOM to be created with namespace support enabled.
 */
private void initNamespaceSupport(Element schemaRoot) {
    fNamespaceSupport = new SchemaNamespaceSupport();
    fNamespaceSupport.reset();

    Node parent = schemaRoot.getParentNode();
    while (parent != null && parent.getNodeType() == Node.ELEMENT_NODE
            && !parent.getNodeName().equals("DOCUMENT_NODE"))
    {
        Element eparent = (Element) parent;
        NamedNodeMap map = eparent.getAttributes();
        int length = (map != null) ? map.getLength() : 0;
        for (int i = 0; i < length; i++) {
            Attr attr = (Attr) map.item(i);
            String uri = attr.getNamespaceURI();

            // Check if attribute is an ns decl -- requires ns support
            if (uri != null && uri.equals("http://www.w3.org/2000/xmlns/")) {
                String prefix = attr.getLocalName().intern();
                if (prefix == "xmlns") prefix = "";
                // Declare prefix if not set -- moving upwards
                if (fNamespaceSupport.getURI(prefix) == null) {
                    fNamespaceSupport.declarePrefix(prefix,
                            attr.getValue().intern());
                }
            }
        }
        parent = parent.getParentNode();
    }
}
 
Example 6
Source File: RangeImpl.java    From openjdk-8 with GNU General Public License v2.0 5 votes vote down vote up
Node nextNode(Node node, boolean visitChildren) {

        if (node == null) return null;

        Node result;
        if (visitChildren) {
            result = node.getFirstChild();
            if (result != null) {
                return result;
            }
        }

        // if hasSibling, return sibling
        result = node.getNextSibling();
        if (result != null) {
            return result;
        }


        // return parent's 1st sibling.
        Node parent = node.getParentNode();
        while (parent != null
               && parent != fDocument
                ) {
            result = parent.getNextSibling();
            if (result != null) {
                return result;
            } else {
                parent = parent.getParentNode();
            }

        } // while (parent != null && parent != fRoot) {

        // end of list, return null
        return null;
    }
 
Example 7
Source File: DOMNamespaceContext.java    From dragonwell8_jdk with GNU General Public License v2.0 5 votes vote down vote up
private void addNamespaces(Node element) {
    if (element.getParentNode() != null) {
        addNamespaces(element.getParentNode());
    }
    if (element instanceof Element) {
        Element el = (Element)element;
        NamedNodeMap map = el.getAttributes();
        for (int x = 0; x < map.getLength(); x++) {
            Attr attr = (Attr)map.item(x);
            if ("xmlns".equals(attr.getPrefix())) {
                namespaceMap.put(attr.getLocalName(), attr.getValue());
            }
        }
    }
}
 
Example 8
Source File: DOMValidatorHelper.java    From JDKSourceCode1.8 with MIT License 5 votes vote down vote up
/** Traverse the DOM and fire events to the schema validator. */
private void validate(Node node) {
    final Node top = node;
    // Performs a non-recursive traversal of the DOM. This
    // will avoid a stack overflow for DOMs with high depth.
    while (node != null) {
        beginNode(node);
        Node next = node.getFirstChild();
        while (next == null) {
            finishNode(node);
            if (top == node) {
                break;
            }
            next = node.getNextSibling();
            if (next == null) {
                node = node.getParentNode();
                if (node == null || top == node) {
                    if (node != null) {
                        finishNode(node);
                    }
                    next = null;
                    break;
                }
            }
        }
        node = next;
    }
}
 
Example 9
Source File: FragmentDialect.java    From cxf with Apache License 2.0 5 votes vote down vote up
/**
 * Process Put requests for InsertAfter mode.
 * @param value Value defined in the Value element.
 * @return Representation element, which is returned as response.
 */
private Representation modifyRepresentationModeInsertAfter(
        List<Node> nodeList,
        ValueType value) {
    if (nodeList.isEmpty()) {
        throw new InvalidExpression();
    }
    Node firstNode = nodeList.get(0);
    Document ownerDocument = firstNode.getOwnerDocument();
    // if firstNode.getOwnerDocument == null the firstNode is ownerDocument
    ownerDocument = ownerDocument == null ? (Document) firstNode : ownerDocument;

    Node parent = firstNode.getParentNode();
    if (parent == null && firstNode.getNodeType() != Node.DOCUMENT_NODE) {
        throw new InvalidExpression();
    }
    if (parent == null) {
        parent = firstNode;
        if (((Document) parent).getDocumentElement() != null) {
            throw new InvalidExpression();
        }
    }

    for (Node node : nodeList) {
        if (node.getNodeType() == Node.ATTRIBUTE_NODE) {
            throw new InvalidRepresentation();
        }
        insertAfter(ownerDocument, parent, node, value);
    }

    Representation representation = new Representation();
    representation.setAny(ownerDocument.getDocumentElement());
    return representation;
}
 
Example 10
Source File: RangeImpl.java    From hottub with GNU General Public License v2.0 5 votes vote down vote up
/** what is the index of the child in the parent */
int indexOf(Node child, Node parent) {
    if (child.getParentNode() != parent) return -1;
    int i = 0;
    for(Node node = parent.getFirstChild(); node!= child; node=node.getNextSibling()) {
        i++;
    }
    return i;
}
 
Example 11
Source File: TreeWalker.java    From openjdk-8-source with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Perform a pre-order traversal non-recursive style.
 *
 * In contrast to the traverse() method this method will not issue
 * startDocument() and endDocument() events to the SAX listener.
 *
 * @param pos Node in the tree where to start traversal
 *
 * @throws TransformerException
 */
public void traverseFragment(Node pos) throws org.xml.sax.SAXException
{
  Node top = pos;

  while (null != pos)
  {
    startNode(pos);

    Node nextNode = pos.getFirstChild();

    while (null == nextNode)
    {
      endNode(pos);

      if (top.equals(pos))
        break;

      nextNode = pos.getNextSibling();

      if (null == nextNode)
      {
        pos = pos.getParentNode();

        if ((null == pos) || (top.equals(pos)))
        {
          if (null != pos)
            endNode(pos);

          nextNode = null;

          break;
        }
      }
    }

    pos = nextNode;
  }
}
 
Example 12
Source File: DOMStreamReader.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Finds the root element node of the traversal.
 */
private Node findRootElement() {
    int type;

    Node node = _start;
    while ((type = node.getNodeType()) != DOCUMENT_NODE
            && type != ELEMENT_NODE) {
        node = node.getParentNode();
    }
    return node;
}
 
Example 13
Source File: DOMValidatorHelper.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
/** Traverse the DOM and fire events to the schema validator. */
private void validate(Node node) {
    final Node top = node;
    // Performs a non-recursive traversal of the DOM. This
    // will avoid a stack overflow for DOMs with high depth.
    while (node != null) {
        beginNode(node);
        Node next = node.getFirstChild();
        while (next == null) {
            finishNode(node);
            if (top == node) {
                break;
            }
            next = node.getNextSibling();
            if (next == null) {
                node = node.getParentNode();
                if (node == null || top == node) {
                    if (node != null) {
                        finishNode(node);
                    }
                    next = null;
                    break;
                }
            }
        }
        node = next;
    }
}
 
Example 14
Source File: DOMNodePointer.java    From commons-jxpath with Apache License 2.0 5 votes vote down vote up
/**
 * Get the ns uri of the specified node.
 * @param node Node to check
 * @return String ns uri
 */
public static String getNamespaceURI(Node node) {
    if (node instanceof Document) {
        node = ((Document) node).getDocumentElement();
    }

    Element element = (Element) node;

    String uri = element.getNamespaceURI();
    if (uri == null) {
        String prefix = getPrefix(node);
        String qname = prefix == null ? "xmlns" : "xmlns:" + prefix;

        Node aNode = node;
        while (aNode != null) {
            if (aNode.getNodeType() == Node.ELEMENT_NODE) {
                Attr attr = ((Element) aNode).getAttributeNode(qname);
                if (attr != null) {
                    uri = attr.getValue();
                    break;
                }
            }
            aNode = aNode.getParentNode();
        }
    }
    return "".equals(uri) ? null : uri;
}
 
Example 15
Source File: CanonicalizerBase.java    From jdk8u-dev-jdk with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Adds to ns the definitions from the parent elements of el
 * @param el
 * @param ns
 */
protected final void getParentNameSpaces(Element el, NameSpaceSymbTable ns)  {
    Node n1 = el.getParentNode();
    if (n1 == null || Node.ELEMENT_NODE != n1.getNodeType()) {
        return;
    }
    //Obtain all the parents of the element
    List<Element> parents = new ArrayList<Element>();
    Node parent = n1;
    while (parent != null && Node.ELEMENT_NODE == parent.getNodeType()) {
        parents.add((Element)parent);
        parent = parent.getParentNode();
    }
    //Visit them in reverse order.
    ListIterator<Element> it = parents.listIterator(parents.size());
    while (it.hasPrevious()) {
        Element ele = it.previous();
        handleParent(ele, ns);
    }
    parents.clear();
    Attr nsprefix;
    if (((nsprefix = ns.getMappingWithoutRendered(XMLNS)) != null)
            && "".equals(nsprefix.getValue())) {
        ns.addMappingAndRender(
                XMLNS, "", getNullNode(nsprefix.getOwnerDocument()));
    }
}
 
Example 16
Source File: TreeWalker.java    From hottub with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Perform a pre-order traversal non-recursive style.

 * Note that TreeWalker assumes that the subtree is intended to represent
 * a complete (though not necessarily well-formed) document and, during a
 * traversal, startDocument and endDocument will always be issued to the
 * SAX listener.
 *
 * @param pos Node in the tree where to start traversal
 * @param top Node in the tree where to end traversal
 *
 * @throws TransformerException
 */
public void traverse(Node pos, Node top) throws org.xml.sax.SAXException
{

      this.m_contentHandler.startDocument();

  while (null != pos)
  {
    startNode(pos);

    Node nextNode = pos.getFirstChild();

    while (null == nextNode)
    {
      endNode(pos);

      if ((null != top) && top.equals(pos))
        break;

      nextNode = pos.getNextSibling();

      if (null == nextNode)
      {
        pos = pos.getParentNode();

        if ((null == pos) || ((null != top) && top.equals(pos)))
        {
          nextNode = null;

          break;
        }
      }
    }

    pos = nextNode;
  }
  this.m_contentHandler.endDocument();
}
 
Example 17
Source File: DOMHelper.java    From jdk8u60 with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Obtain the XPath-model parent of a DOM node -- ownerElement for Attrs,
 * parent for other nodes.
 * <p>
 * Background: The DOM believes that you must be your Parent's
 * Child, and thus Attrs don't have parents. XPath said that Attrs
 * do have their owning Element as their parent. This function
 * bridges the difference, either by using the DOM Level 2 ownerElement
 * function or by using a "silly and expensive function" in Level 1
 * DOMs.
 * <p>
 * (There's some discussion of future DOMs generalizing ownerElement
 * into ownerNode and making it work on all types of nodes. This
 * still wouldn't help the users of Level 1 or Level 2 DOMs)
 * <p>
 *
 * @param node Node whose XPath parent we want to obtain
 *
 * @return the parent of the node, or the ownerElement if it's an
 * Attr node, or null if the node is an orphan.
 *
 * @throws RuntimeException if the Document has no root element.
 * This can't arise if the Document was created
 * via the DOM Level 2 factory methods, but is possible if other
 * mechanisms were used to obtain it
 */
public static Node getParentOfNode(Node node) throws RuntimeException
{
  Node parent;
  short nodeType = node.getNodeType();

  if (Node.ATTRIBUTE_NODE == nodeType)
  {
    Document doc = node.getOwnerDocument();
        /*
    TBD:
    if(null == doc)
    {
      throw new RuntimeException(XSLMessages.createXPATHMessage(XPATHErrorResources.ER_CHILD_HAS_NO_OWNER_DOCUMENT, null));//"Attribute child does not have an owner document!");
    }
    */

        // Given how expensive the tree walk may be, we should first ask
        // whether this DOM can answer the question for us. The additional
        // test does slow down Level 1 DOMs slightly. DOMHelper2, which
        // is currently specialized for Xerces, assumes it can use the
        // Level 2 solution. We might want to have an intermediate stage,
        // which would assume DOM Level 2 but not assume Xerces.
        //
        // (Shouldn't have to check whether impl is null in a compliant DOM,
        // but let's be paranoid for a moment...)
        DOMImplementation impl=doc.getImplementation();
        if(impl!=null && impl.hasFeature("Core","2.0"))
        {
                parent=((Attr)node).getOwnerElement();
                return parent;
        }

        // DOM Level 1 solution, as fallback. Hugely expensive.

    Element rootElem = doc.getDocumentElement();

    if (null == rootElem)
    {
      throw new RuntimeException(
        XMLMessages.createXMLMessage(
          XMLErrorResources.ER_CHILD_HAS_NO_OWNER_DOCUMENT_ELEMENT,
          null));  //"Attribute child does not have an owner document element!");
    }

    parent = locateAttrParent(rootElem, node);

      }
  else
  {
    parent = node.getParentNode();

    // if((Node.DOCUMENT_NODE != nodeType) && (null == parent))
    // {
    //   throw new RuntimeException("Child does not have parent!");
    // }
  }

  return parent;
}
 
Example 18
Source File: DOMUtil.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Copies the source tree into the specified place in a destination
 * tree. The source node and its children are appended as children
 * of the destination node.
 * <p>
 * <em>Note:</em> This is an iterative implementation.
 */
public static void copyInto(Node src, Node dest) throws DOMException {

    // get node factory
    Document factory = dest.getOwnerDocument();
    boolean domimpl = factory instanceof DocumentImpl;

    // placement variables
    Node start  = src;
    Node parent = src;
    Node place  = src;

    // traverse source tree
    while (place != null) {

        // copy this node
        Node node = null;
        int  type = place.getNodeType();
        switch (type) {
        case Node.CDATA_SECTION_NODE: {
            node = factory.createCDATASection(place.getNodeValue());
            break;
        }
        case Node.COMMENT_NODE: {
            node = factory.createComment(place.getNodeValue());
            break;
        }
        case Node.ELEMENT_NODE: {
            Element element = factory.createElement(place.getNodeName());
            node = element;
            NamedNodeMap attrs  = place.getAttributes();
            int attrCount = attrs.getLength();
            for (int i = 0; i < attrCount; i++) {
                Attr attr = (Attr)attrs.item(i);
                String attrName = attr.getNodeName();
                String attrValue = attr.getNodeValue();
                element.setAttribute(attrName, attrValue);
                if (domimpl && !attr.getSpecified()) {
                    ((AttrImpl)element.getAttributeNode(attrName)).setSpecified(false);
                }
            }
            break;
        }
        case Node.ENTITY_REFERENCE_NODE: {
            node = factory.createEntityReference(place.getNodeName());
            break;
        }
        case Node.PROCESSING_INSTRUCTION_NODE: {
            node = factory.createProcessingInstruction(place.getNodeName(),
                    place.getNodeValue());
            break;
        }
        case Node.TEXT_NODE: {
            node = factory.createTextNode(place.getNodeValue());
            break;
        }
        default: {
            throw new IllegalArgumentException("can't copy node type, "+
                    type+" ("+
                    place.getNodeName()+')');
        }
        }
        dest.appendChild(node);

        // iterate over children
        if (place.hasChildNodes()) {
            parent = place;
            place  = place.getFirstChild();
            dest   = node;
        }

        // advance
        else {
            place = place.getNextSibling();
            while (place == null && parent != start) {
                place  = parent.getNextSibling();
                parent = parent.getParentNode();
                dest   = dest.getParentNode();
            }
        }

    }

}
 
Example 19
Source File: XMLUtils.java    From jdk8u-jdk with GNU General Public License v2.0 4 votes vote down vote up
/**
 * This is the work horse for {@link #circumventBug2650}.
 *
 * @param node
 * @see <A HREF="http://nagoya.apache.org/bugzilla/show_bug.cgi?id=2650">
 * Namespace axis resolution is not XPath compliant </A>
 */
@SuppressWarnings("fallthrough")
private static void circumventBug2650internal(Node node) {
    Node parent = null;
    Node sibling = null;
    final String namespaceNs = Constants.NamespaceSpecNS;
    do {
        switch (node.getNodeType()) {
        case Node.ELEMENT_NODE :
            Element element = (Element) node;
            if (!element.hasChildNodes()) {
                break;
            }
            if (element.hasAttributes()) {
                NamedNodeMap attributes = element.getAttributes();
                int attributesLength = attributes.getLength();

                for (Node child = element.getFirstChild(); child!=null;
                    child = child.getNextSibling()) {

                    if (child.getNodeType() != Node.ELEMENT_NODE) {
                        continue;
                    }
                    Element childElement = (Element) child;

                    for (int i = 0; i < attributesLength; i++) {
                        Attr currentAttr = (Attr) attributes.item(i);
                        if (!namespaceNs.equals(currentAttr.getNamespaceURI())) {
                            continue;
                        }
                        if (childElement.hasAttributeNS(namespaceNs,
                                                        currentAttr.getLocalName())) {
                            continue;
                        }
                        childElement.setAttributeNS(namespaceNs,
                                                    currentAttr.getName(),
                                                    currentAttr.getNodeValue());
                    }
                }
            }
        case Node.ENTITY_REFERENCE_NODE :
        case Node.DOCUMENT_NODE :
            parent = node;
            sibling = node.getFirstChild();
            break;
        }
        while ((sibling == null) && (parent != null)) {
            sibling = parent.getNextSibling();
            parent = parent.getParentNode();
        }
        if (sibling == null) {
            return;
        }

        node = sibling;
        sibling = node.getNextSibling();
    } while (true);
}
 
Example 20
Source File: XMLUtils.java    From openjdk-8 with GNU General Public License v2.0 4 votes vote down vote up
/**
 * This method is a tree-search to help prevent against wrapping attacks. It checks that no other
 * Element than the given "knownElement" argument has an ID attribute that matches the "value"
 * argument, which is the ID value of "knownElement". If this is the case then "false" is returned.
 */
public static boolean protectAgainstWrappingAttack(
    Node startNode, Element knownElement, String value
) {
    Node startParent = startNode.getParentNode();
    Node processedNode = null;

    String id = value.trim();
    if (id.charAt(0) == '#') {
        id = id.substring(1);
    }

    while (startNode != null) {
        if (startNode.getNodeType() == Node.ELEMENT_NODE) {
            Element se = (Element) startNode;

            NamedNodeMap attributes = se.getAttributes();
            if (attributes != null) {
                for (int i = 0; i < attributes.getLength(); i++) {
                    Attr attr = (Attr)attributes.item(i);
                    if (attr.isId() && id.equals(attr.getValue()) && se != knownElement) {
                        log.log(java.util.logging.Level.FINE, "Multiple elements with the same 'Id' attribute value!");
                        return false;
                    }
                }
            }
        }

        processedNode = startNode;
        startNode = startNode.getFirstChild();

        // no child, this node is done.
        if (startNode == null) {
            // close node processing, get sibling
            startNode = processedNode.getNextSibling();
        }

        // no more siblings, get parent, all children
        // of parent are processed.
        while (startNode == null) {
            processedNode = processedNode.getParentNode();
            if (processedNode == startParent) {
                return true;
            }
            // close parent node processing (processed node now)
            startNode = processedNode.getNextSibling();
        }
    }
    return true;
}