Returns the owner element of the node and null if not found. - Java XML

Java examples for XML:XML Element Parent

Description

Returns the owner element of the node and null if not found.

Demo Code

/**/*from  w  w w  .  j a v a2  s  .c  o  m*/
 *  Copyright (c) 2013-2014 Angelo ZERR.
 *  All rights reserved. This program and the accompanying materials
 *  are made available under the terms of the Eclipse Public License v1.0
 *  which accompanies this distribution, and is available at
 *  http://www.eclipse.org/legal/epl-v10.html
 *
 *  Contributors:
 *  Angelo Zerr <angelo.zerr@gmail.com> - initial API and implementation
 */
//package com.java2s;

import org.w3c.dom.Attr;
import org.w3c.dom.CDATASection;

import org.w3c.dom.Element;
import org.w3c.dom.Node;

import org.w3c.dom.Text;

public class Main {
    /**
     * Returns the owner element of the node and null if not found.
     * 
     * @param node
     * @return
     */
    public static Element getOwnerElement(Node node) {
        int nodeType = node.getNodeType();
        switch (nodeType) {
        case Node.ATTRIBUTE_NODE:
            return ((Attr) node).getOwnerElement();
        case Node.TEXT_NODE:
            return (Element) ((Text) node).getParentNode();
        case Node.CDATA_SECTION_NODE:
            return (Element) ((CDATASection) node).getParentNode();
        case Node.ELEMENT_NODE:
            return (Element) node;
        }
        return null;
    }
}

Related Tutorials