devxlogo

Put an XPath Expression into a Java Application

Put an XPath Expression into a Java Application

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.

devxblackblue

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist