Java XML Node Parent getParentElement(Element element)

Here you can find the source of getParentElement(Element element)

Description

Gets the parent element.

License

Open Source License

Parameter

Parameter Description
element the element

Return

the parent element

Declaration

public static Element getParentElement(Element element) 

Method Source Code

//package com.java2s;

import org.w3c.dom.Document;
import org.w3c.dom.Element;

import org.w3c.dom.Node;

public class Main {
    /**//from  w  ww  .  j a  v a 2 s .  c  o m
     * Gets the parent element.
     * 
     * @param element
     *            the element
     * @return the parent element
     */
    public static Element getParentElement(Element element) {
        if (element == null) {
            return null;
        }
        Element parentElement = null;
        Node parentNode = element.getParentNode();
        while (parentNode != null && parentElement == null) {
            if (parentNode.getNodeType() == Node.ELEMENT_NODE) {
                parentElement = (Element) parentNode;
            }
            if (parentNode.getNodeType() == Node.DOCUMENT_NODE) {
                parentElement = ((Document) parentNode).getDocumentElement();
                if (element.isSameNode(parentElement)) {
                    parentElement = null;
                }
            }
            parentNode = parentNode.getParentNode();
        }

        return parentElement;
    }
}

Related

  1. getParent(Element elem)
  2. getParent(final Node n)
  3. getParent(Node node)
  4. getParent(Node target)
  5. getParentElement(Element element)
  6. getParentElement(final Node node)
  7. getParentElement(Node node)
  8. getParentElement(Node node)
  9. getParentElement(Node node)