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

Open Source License

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;
/*//from   w  w w  . j a  v  a 2  s .  c  om
 *  soapUI, copyright (C) 2004-2010 eviware.com 
 *
 *  soapUI is free software; you can redistribute it and/or modify it under the 
 *  terms of version 2.1 of the GNU Lesser General Public License as published by 
 *  the Free Software Foundation.
 *
 *  soapUI is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without 
 *  even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. 
 *  See the GNU Lesser General Public License for more details at gnu.org.
 */

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. getElementNS(Element el, String nsuri, String name)
  2. getElementNS(Element elem, String namespaceUri, String localName)
  3. getElementNS(Element root, Set nsUris, String wantedLocalName)
  4. getElementPath(Element elem)
  5. getElementPath(Element element)
  6. getElementPosition(Element element)
  7. getElements(Element aElement)
  8. getElements(Element document, String elementName, String attrName, String attrValue)
  9. getElements(Element elem, String path)