Inserting an XPath Expression into a Java Application can be very useful if you need to develop a Java application that evaluates a simple XPath expression. Just a copy/paste your own XPath expression and XML document, like this:
import javax.xml.xpath.*;import java.io.*;import org.xml.sax.InputSource;public class XPathExample{ InputSource IS=null; XPathExpression XPE=null; public XPathExample(){} public void evaluateXPath(File XMLdoc){ //XPathFactory object XPathFactory XPF=XPathFactory.newInstance(); //XPath object XPath XP=XPF.newXPath(); //XPath expression try{ XPE=XP.compile("your_XPath_expression"); }catch(javax.xml.xpath.XPathExpressionException e) {System.err.println("e:"+e.getMessage());} //XML document try{ IS=new InputSource(new FileInputStream(XMLdoc)); }catch(java.io.FileNotFoundException e) {System.err.println(e.getMessage());} //evaluation of the XPath try{ String result=XPE.evaluate(IS); System.out.println("Result:
"+ result); }catch(javax.xml.xpath.XPathExpressionException e) {System.err.println(e.getMessage());} }public static void main(String[] argv) { XPathExample t=new XPathExample(); File XMLdoc=new File("your_XML_file"); t.evaluateXPath(XMLdoc); }}
Note: Don’t use this technique in XPath expressions that evaluate to node-sets?use it only when an expression returns an atomic value.