find Node By XPath - Java XML

Java examples for XML:XPath

Description

find Node By XPath

Demo Code

/*//from   w  ww.ja va2  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.util.StringTokenizer;

import org.w3c.dom.Node;

public class Main {
    public static Node findNodeByXPath(Node base, String xpath) {
        if ("/".equals(xpath)) {
            return base;
        }
        Node node = base;
        StringTokenizer tok = new StringTokenizer(xpath, "/");
        while (tok.hasMoreTokens()) {
            String subpath = tok.nextToken();
            String localName;
            int nodePos = 0;
            int index = subpath.indexOf('[');
            if (index > 0) {
                localName = subpath.substring(0, index).toLowerCase();
                nodePos = Integer.parseInt(subpath.substring(index + 1,
                        subpath.indexOf(']')));
            } else {
                localName = subpath.toLowerCase();
            }
            short nodeType = Node.ELEMENT_NODE;
            if ("text()".equals(localName)) {
                nodeType = Node.TEXT_NODE;
                localName = "";
            }
            node = node.getFirstChild();
            int pos = 0;
            while (node != null) {
                if (node.getNodeType() == nodeType
                        && localName.equals(node.getLocalName()
                                .toLowerCase())) {
                    if (pos == nodePos) {
                        break;
                    }
                    ++pos;
                }
                node = node.getNextSibling();
            }
        }
        return node;
        /*
        try {
            XPathFactory factory = XPathFactory.newInstance();
            XPath xpath = factory.newXPath();
            XPathExpression expr = xpath.compile(path);
            return (Node) expr.evaluate(document, XPathConstants.NODE);
        } catch (XPathExpressionException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (DOMException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
         */

    }
}

Related Tutorials