Thursday, October 18, 2018

XPath using JAXP

 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());
        }
    }
}

No comments:

Post a Comment

CORBA Java Tutorial using Netbeans and Java 8.

CORBA-Example A simple CORBA implementation using Java Echo.idl module EchoApp{ interface Echo{ string echoString(); }; }; ...