Login | Register   
Twitter
RSS Feed
Download our iPhone app
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
Browse DevX
Sign up for e-mail newsletters from DevX


Tip of the Day
Language: Java
Expertise: Intermediate
Feb 19, 2008

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: \n "+ 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.

Leonard Anghel
 
Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

Sitemap