Java XPath Create getXPath(Node n)

Here you can find the source of getXPath(Node n)

Description

Constructs a XPath query to the supplied node.

License

Creative Commons License

Parameter

Parameter Description
n a parameter

Declaration

public static String getXPath(Node n) 

Method Source Code

//package com.java2s;
/**/*w  w  w . jav a2s. c  o m*/
 * Utility class for dealing with XML DOM elements.
 * 
 * ********************************************************************* ***
 * DISCLAIMER *** This code is covered by the Creative Commons Attribution 2.5
 * License (http://creativecommons.org/licenses/by/2.5/).
 * 
 * You may use this code in any way you see fit as long as you realize that the
 * code is provided AS IS without any warrenties and confers to rights what so
 * ever! The author cannot be held accountable for any loss, direct or indirect,
 * afflicted by using the code.
 * 
 * *********************************************************************
 * 
 * 
 * @author Mikkel Heisterberg, lekkim@lsdoc.org
 */

import java.util.ArrayList;
import java.util.Iterator;
import org.w3c.dom.Node;

public class Main {
    /**
     * Constructs a XPath query to the supplied node.
     * 
     * @param n
     * @return
     */
    public static String getXPath(Node n) {
        if (null == n) {
            throw new IllegalArgumentException("Invalid node");
        }

        ArrayList<Node> hierarchy = new ArrayList<Node>();
        StringBuffer buffer = new StringBuffer();
        Node parent = null;

        // Push parent element's on stack
        hierarchy.add(n);
        parent = n.getParentNode();
        while (parent != null && parent.getNodeType() != Node.DOCUMENT_NODE) {
            hierarchy.add(0, parent);
            parent = parent.getParentNode();
        }

        Iterator<Node> i = hierarchy.iterator();
        while (i.hasNext()) {
            Node node = i.next();
            buffer.append("/");
            buffer.append(node.getNodeName());
            if (node.hasAttributes()) {
                Node uuid = node.getAttributes().getNamedItem("uuid");
                if (uuid != null) {
                    buffer.append("[@uuid='");
                    buffer.append(uuid.getNodeValue());
                    buffer.append("']");
                }
            }
        }

        // return buffer
        return buffer.toString();
    }
}

Related

  1. getXPath(Element elt)
  2. getXPath(Element rootElement, Element targetElement, boolean includeElementIndex, Map namespacesMap)
  3. getXPath(NamespaceContext nsContext)
  4. getXPath(Node n)
  5. getXPath(Node n)
  6. getXPath(Node n)
  7. getXPath(Node node)
  8. getXPath(Node node)
  9. getXPath(Node node)