Java XPath Create getXPath(Node n)

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

Description

Creates XPath expression for a given DOM node

License

Open Source License

Parameter

Parameter Description
n a DOM node

Return

an XPath expression of the node representing node location in the document

Declaration

public static String getXPath(Node n) 

Method Source Code

//package com.java2s;
/*//from w ww . j  ava  2  s. co m
 * #%L
 * Xacml4J Core Engine Implementation
 * %%
 * Copyright (C) 2009 - 2014 Xacml4J.org
 * %%
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License as
 * published by the Free Software Foundation, either version 3 of the
 * License, or (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Lesser Public License for more details.
 * 
 * You should have received a copy of the GNU General Lesser Public
 * License along with this program.  If not, see
 * <http://www.gnu.org/licenses/lgpl-3.0.html>.
 * #L%
 */

import java.util.Stack;

import org.w3c.dom.Attr;

import org.w3c.dom.Element;
import org.w3c.dom.Node;

import com.google.common.base.Preconditions;
import com.google.common.base.Strings;

public class Main {
    /**
     * Creates XPath expression for a given DOM node
     * @param n a DOM node
     * @return an XPath expression of the node
     * representing node location in the document
     */
    public static String getXPath(Node n) {
        Preconditions.checkNotNull(n);
        Stack<Node> hierarchy = new Stack<Node>();
        StringBuilder buffer = new StringBuilder();
        hierarchy.push(n);
        Node parent = getParent(n);
        while (parent != null) {
            hierarchy.push(parent);
            if (parent.getNodeType() == Node.DOCUMENT_NODE) {
                break;
            }
            parent = getParent(parent);
        }
        Node node = null;
        Node previous = null;
        while (!hierarchy.isEmpty() && (node = hierarchy.pop()) != null) {
            if (node.getNodeType() == Node.DOCUMENT_NODE) {
                buffer.append("//");
            }
            if (node.getNodeType() == Node.ELEMENT_NODE) {
                if (previous != null
                        && previous.getNodeType() != Node.DOCUMENT_NODE) {
                    buffer.append('/');
                }
                buffer.append(node.getNodeName());
                if (previous != null
                        && previous.getNodeType() != Node.DOCUMENT_NODE) {
                    buffer.append('[').append(getNodeIndex(node))
                            .append(']');
                }
            }
            if (node.getNodeType() == Node.TEXT_NODE) {
                buffer.append("/text()");
                continue;
            }
            if (node.getNodeType() == Node.ATTRIBUTE_NODE) {
                Attr attr = (Attr) node;
                buffer.append("/@").append(attr.getName());
            }
            previous = node;
        }
        return buffer.toString();
    }

    /**
     * Gets parent node of the given node
     *
     * @param node a DOM node
     * @return a parent node {@link Node} instance
     */
    private static Node getParent(Node node) {
        return (node.getNodeType() == Node.ATTRIBUTE_NODE) ? ((Attr) node)
                .getOwnerElement() : node.getParentNode();
    }

    /**
     * Gets node index relative to its siblings
     *
     * @param node a node
     * @return a node index
     */
    private static int getNodeIndex(Node node) {
        Preconditions.checkNotNull(node);
        int prev_siblings = 1;
        Node prev_sibling = node.getPreviousSibling();
        while (prev_sibling != null) {
            if (prev_sibling.getNodeType() == node.getNodeType()) {
                if (prev_sibling.getNodeName().equalsIgnoreCase(
                        node.getNodeName())) {
                    prev_siblings++;
                }
            }
            prev_sibling = prev_sibling.getPreviousSibling();
        }
        return prev_siblings;
    }

    /**
     * Creates a {@link String} representation
     *
     * @param n a DOM node
     * @return a string representation
     */
    public static String toString(Element n) {
        if (n == null) {
            return null;
        }
        StringBuilder fqname = new StringBuilder();
        if (!Strings.isNullOrEmpty(n.getNamespaceURI())) {
            fqname.append('{').append(n.getNamespaceURI()).append('}');
        }
        fqname.append(n.getLocalName());
        return fqname.toString();
    }
}

Related

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