Here you can find the source of getElementPath(Element element)
Parameter | Description |
---|---|
element | the element to create for |
public static String getElementPath(Element element)
//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; } }