dcsimg
Login | Register   
LinkedIn
Google+
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

By submitting your information, you agree that devx.com may send you DevX offers via email, phone and text message, as well as email offers about other products and services that DevX believes may be of interest to you. DevX will process your information in accordance with the Quinstreet Privacy Policy.


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

WEBINAR:

On-Demand

Building the Right Environment to Support AI, Machine Learning and Deep Learning


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
Thanks for your registration, follow us on our social networks to keep up-to-date