Here you can find the source of findNodeByXPath(Node base, String xpath)
public static Node findNodeByXPath(Node base, String xpath)
//package com.java2s; /*/*from w ww . java 2s . co m*/ * (C) Copyright 2006-2007 Nuxeo SA (http://nuxeo.com/) and others. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * Contributors: * Max Stepanov * * $Id$ */ 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(); } */ } }