compute Node XPath between two XML node - Java XML

Java examples for XML:XPath

Description

compute Node XPath between two XML node

Demo Code

/*/*w ww  .  j a  v  a  2  s .co m*/
 * (C) Copyright 2006-2007 Nuxeo SAS (http://nuxeo.com/) and contributors.
 *
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the GNU Lesser General Public License
 * (LGPL) version 2.1 which accompanies this distribution, and is available at
 * http://www.gnu.org/licenses/lgpl.html
 *
 * This library 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
 * Lesser General Public License for more details.
 *
 * Contributors:
 *     Max Stepanov
 *
 * $Id$
 */
//package com.java2s;
import java.text.MessageFormat;

import org.w3c.dom.Node;

public class Main {
    public static String computeNodeXPath(Node base, Node node) {
        if (base.isSameNode(node)) {
            return "/";
        }
        short nodeType = node.getNodeType();
        String subpath;
        if (nodeType == Node.ELEMENT_NODE || nodeType == Node.TEXT_NODE) {
            String localName = node.getLocalName().toLowerCase();
            int pos = 0;
            Node sibling = node.getPreviousSibling();
            while (sibling != null) {
                if (sibling.getNodeType() == nodeType) {
                    if (localName.equals(sibling.getLocalName()
                            .toLowerCase())) {
                        ++pos;
                    }
                }
                sibling = sibling.getPreviousSibling();
            }
            if (nodeType == Node.TEXT_NODE) {
                localName = "text()";
            }

            if (pos == 0) {
                subpath = localName;
            } else {
                subpath = MessageFormat.format("{0}[{1}]", localName,
                        new Integer(pos));
            }
        } else {
            System.err.println("Unsupported type " + nodeType);
            subpath = "unknown";
        }
        Node parent = node.getParentNode();
        if (base.isSameNode(parent)) {
            return '/' + subpath;
        } else {
            return computeNodeXPath(base, parent) + '/' + subpath;
        }
    }
}

Related Tutorials