Here you can find the source of findNodeByXpath(String xpathExpression, String fileName)
public static Node findNodeByXpath(String xpathExpression, String fileName)
//package com.java2s; /******************************************************************************* * Copyright (c) 2015 UNIT Information Technologies R&D Ltd * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors://w ww. j av a 2 s . c o m * Ferhat Erata - initial API and implementation * H. Emre Kirmizi - initial API and implementation * Serhat Celik - initial API and implementation * U. Anil Ozturk - initial API and implementation *******************************************************************************/ import java.io.File; import java.io.IOException; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import javax.xml.xpath.XPath; import javax.xml.xpath.XPathConstants; import javax.xml.xpath.XPathExpressionException; import javax.xml.xpath.XPathFactory; import org.w3c.dom.Document; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.xml.sax.SAXException; public class Main { public static Node findNodeByXpath(String xpathExpression, String fileName) { DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); dbf.setValidating(false); DocumentBuilder db; Document doc; try { db = dbf.newDocumentBuilder(); doc = db.parse(new File(fileName)); XPath xpath = XPathFactory.newInstance().newXPath(); NodeList nodes = (NodeList) xpath.evaluate(xpathExpression, doc, XPathConstants.NODESET); for (int i = 0; i < nodes.getLength(); i++) { System.out.print(nodes.item(i).getNodeName() + " "); } if (nodes.getLength() > 1) return nodes.item(0); } catch (ParserConfigurationException e) { e.printStackTrace(); } catch (SAXException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (XPathExpressionException e) { e.printStackTrace(); } return null; } }