Java XPath Create getXPathExpression(final Node node)

Here you can find the source of getXPathExpression(final Node node)

Description

Returns the unique XPath expression for the given node.

License

Open Source License

Parameter

Parameter Description
node The node to determine the XPath for

Return

The XPath expression as string

Declaration

private static String getXPathExpression(final Node node) 

Method Source Code

//package com.java2s;
/*******************************************************************************
 * Copyright (c) 2009 Dominik Schadow - http://www.xml-sicherheit.de All rights reserved. This
 * program and the accompanying materials are made available under the terms of the Eclipse Public
 * License v1.0 which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 *
 * Contributors: Dominik Schadow - initial API and implementation
 *******************************************************************************/

import org.w3c.dom.Document;

import org.w3c.dom.Node;

public class Main {
    /**//from  ww  w  .ja  va 2 s . com
     * Returns the unique XPath expression for the given node.
     *
     * @param node The node to determine the XPath for
     * @return The XPath expression as string
     */
    private static String getXPathExpression(final Node node) {
        String xpathExpression = node.getNodeName();

        if (node.getParentNode() != null) {
            int index = 0;
            Node prec = node;

            while (prec != null) {
                if (prec.getNodeName().equals(node.getNodeName())) {
                    index++;
                }
                prec = prec.getPreviousSibling();
            }

            if (node.getParentNode() instanceof Document) {
                ; // do nothing
            } else {
                xpathExpression = getXPathExpression(node.getParentNode()) + "/" + xpathExpression //$NON-NLS-1$
                        + "[" + String.valueOf(index) + "]"; //$NON-NLS-1$ //$NON-NLS-2$
            }
        }

        return xpathExpression;
    }
}

Related

  1. getXPath(Node node)
  2. getXPath(Node node)
  3. getXPath(Node node, String xpath)
  4. getXPath(String exp, NamespaceContext ctx)
  5. getXPath(String expression)
  6. getXPathExpression(String expression)
  7. getXPathExpression(String path)
  8. getXPathExpression(String xpath, NamespaceContext namespaceContext)
  9. getXPathExpression(String xpathStr)