Java XML Element Get getElementPath(Element element)

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

Description

Returns absolute xpath for specified element, ignores namespaces

License

EUPL

Parameter

Parameter Description
element the element to create for

Return

the elements path in its containing document

Declaration


public static String getElementPath(Element element) 

Method Source Code

//package com.java2s;
/*// w  ww . j  a v  a2s . c o m
 * Copyright 2004-2014 SmartBear Software
 *
 * Licensed under the EUPL, Version 1.1 or - as soon as they will be approved by the European Commission - subsequent
 * versions of the EUPL (the "Licence");
 * You may not use this work except in compliance with the Licence.
 * You may obtain a copy of the Licence at:
 *
 * http://ec.europa.eu/idabc/eupl
 *
 * Unless required by applicable law or agreed to in writing, software distributed under the Licence is
 * distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
 * express or implied. See the Licence for the specific language governing permissions and limitations
 * under the Licence.
*/

import org.w3c.dom.Element;

import org.w3c.dom.Node;

public class Main {
    /**
     * Returns absolute xpath for specified element, ignores namespaces
     *
     * @param element the element to create for
     * @return the elements path in its containing document
     */

    public static String getElementPath(Element element) {
        Node elm = element;

        String result = elm.getNodeName() + "[" + getElementIndex(elm) + "]";
        while (elm.getParentNode() != null && elm.getParentNode().getNodeType() != Node.DOCUMENT_NODE) {
            elm = elm.getParentNode();
            result = elm.getNodeName() + "[" + getElementIndex(elm) + "]/" + result;
        }

        return "/" + result;
    }

    /**
     * Gets the index of the specified element amongst elements with the same
     * name
     *
     * @param element the element to get for
     * @return the index of the element, will be >= 1
     */

    public static int getElementIndex(Node element) {
        int result = 1;

        Node elm = element.getPreviousSibling();
        while (elm != null) {
            if (elm.getNodeType() == Node.ELEMENT_NODE && elm.getNodeName().equals(element.getNodeName())) {
                result++;
            }
            elm = elm.getPreviousSibling();
        }

        return result;
    }
}

Related

  1. getElementNamespaceURI(Element element)
  2. getElementNS(Element el, String nsuri, String name)
  3. getElementNS(Element elem, String namespaceUri, String localName)
  4. getElementNS(Element root, Set nsUris, String wantedLocalName)
  5. getElementPath(Element elem)
  6. getElementPath(Element element)
  7. getElementPosition(Element element)
  8. getElements(Element aElement)
  9. getElements(Element document, String elementName, String attrName, String attrValue)