Here you can find the source of getXPathForNode(Node node)
Parameter | Description |
---|---|
node | the input node. |
public static String getXPathForNode(Node node)
//package com.java2s; /*//from w ww .j a v a 2 s .c o m * Copyright 2008-2010 Digital Enterprise Research Institute (DERI) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import org.w3c.dom.Node; public class Main { /** * Does a reverse walking of the DOM tree to generate a unique XPath * expression leading to this node. The XPath generated is the canonical * one based on sibling index: /html[1]/body[1]/div[2]/span[3] etc.. * * @param node the input node. * @return the XPath location of node as String. */ public static String getXPathForNode(Node node) { String index = ""; if (node.getNodeType() == Node.ELEMENT_NODE) { int successors = 1; Node previous = node.getPreviousSibling(); while (null != previous) { if (previous.getNodeType() == Node.ELEMENT_NODE && previous.getNodeName().equals(node.getNodeName())) { successors++; } previous = previous.getPreviousSibling(); } index = "/" + node.getNodeName() + "[" + successors + "]"; } Node parent = node.getParentNode(); if (null == parent) return index; else return getXPathForNode(parent) + index; } }