Java XML Node Parent getParentOfNode(Node node)

Here you can find the source of getParentOfNode(Node node)

Description

Get the XPath-model parent of a node.

License

Apache License

Parameter

Parameter Description
node Node to be examined

Return

the DOM parent of the input node, if there is one, or the ownerElement if the input node is an Attr, or null if the node is a Document, a DocumentFragment, or an orphan.

Declaration

public static Node getParentOfNode(Node node) 

Method Source Code

//package com.java2s;
/*//from   www .j  av  a  2s  .  c o  m
 * Copyright 1999-2004 The Apache Software Foundation.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import org.w3c.dom.Attr;

import org.w3c.dom.Node;

public class Main {
    /**
     * Get the XPath-model parent of a node.  This version takes advantage
     * of the DOM Level 2 Attr.ownerElement() method; the base version we
     * would otherwise inherit is prepared to fall back on exhaustively
     * walking the document to find an Attr's parent.
     *
     * @param node Node to be examined
     *
     * @return the DOM parent of the input node, if there is one, or the
     * ownerElement if the input node is an Attr, or null if the node is
     * a Document, a DocumentFragment, or an orphan.
     */
    public static Node getParentOfNode(Node node) {
        Node parent = node.getParentNode();
        if (parent == null && (Node.ATTRIBUTE_NODE == node.getNodeType()))
            parent = ((Attr) node).getOwnerElement();
        return parent;
    }
}

Related

  1. getParentElement(Node node)
  2. getParentElement(Node node)
  3. getParentNamespaces(Element el)
  4. getParentNode(Node node)
  5. getParentNodeNoEx(Node node, String name)
  6. getParentOfNode(Node node)
  7. getParents(Node node)
  8. isAncestor(Node ancestor, Node node)
  9. isAncestorOf(Node ancestor, Node node)