XPath using JAXP

Last Modified On : 22-Oct-2009

import java.util.Scanner;
import javax.xml.xpath.*;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;

public class XPathDemo {
    
    public static void main(String[] args) {
        //  associate Scanner with keyboard
        Scanner s = new Scanner(System.in); 
        try 
        {
         XPathFactory x = XPathFactory.newInstance();
         XPath path = x.newXPath();
         while ( true )
         {
          // take xpath expression from user
          System.out.println("Enter XPATH expression : ");
          String expression = s.nextLine();
          if ( expression.length() == 0 ) 
               break;
          // read content from  team.xml from c:\xml folder. Change it accordingly
          InputSource source = new InputSource("c:\\xml\\team.xml");
          try 
          {
           // search source using xpath expression
           NodeList nl = (NodeList) path.evaluate( expression, source, XPathConstants.NODESET); 
           
           // display selected nodes
           for ( int i = 0 ; i < nl.getLength(); i ++)
              System.out.printf("%s : %s\n", nl.item(i).getNodeName(), nl.item(i).getTextContent());
          }
          catch(Exception ex) {
             System.out.println("Invalid XPath Expression");
          }
         } // end of while 
        }
        catch(Exception ex) {
            System.out.println(ex.getMessage());
        }
    }
}