Java XPath Create getXPathForNode(Node node)

Here you can find the source of getXPathForNode(Node node)

Description

Does a reverse walking of the DOM tree to generate a unique XPath expression leading to this node.

License

Apache License

Parameter

Parameter Description
node the input node.

Return

the XPath location of node as String.

Declaration

public static String getXPathForNode(Node node) 

Method Source Code

//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;
    }
}

Related

  1. getXPathFactory()
  2. getXPathFactory()
  3. getXpathFilter(String xpath, Map namespaceMap)
  4. getXPathForElement(Node e, NamespaceContext ctx)
  5. getXPathForNode(Node node)
  6. getXPathFromVector(Vector path)
  7. getXPathFromVector(Vector path)
  8. getXPathFromVector(Vector path)
  9. getXPathListForNode(Node n)