XPathTest.java



import javax.xml.parsers.*;
import javax.xml.transform.TransformerException;
import org.xml.sax.InputSource;
import org.w3c.dom.*;
import org.apache.xpath.XPathAPI;

/** XPath pattern match test */
public class XPathTest {

  /** use get DOM */
    private DocumentBuilderFactory dbf;
    private DocumentBuilder db;

  /** Constructor */
    public XPathTest() {
        try {
            dbf = DocumentBuilderFactory.newInstance();
            db = dbf.newDocumentBuilder();
        }
        catch( Exception e ) {
            System.err.println( e.toString() );
        }
    }

  /** search xpath pattern and print */
    public void search( Node node, String pattern ) {
        try {

            NodeList list
               = XPathAPI.selectNodeList( node, pattern);
            if( list == null || list.getLength() == 0 ) {
                System.out.println( "Pattern not matched" );
                return;
            }
            for( int i=0; i<list.getLength(); i++ ) {

                Node n = list.item( i );
                System.out.println( n.getNodeName() );
            }
        }
        catch( TransformerException e ) {
            System.err.println( "Pattern not correct" );
        }
        catch( Exception e ) {
            System.err.println( e.toString() );
        }
    }

  /** start here */
    public static void main( String[] argv ) {
        try {
            XPathTest test = new XPathTest();
            InputSource source = new InputSource( argv[1] );
            Document doc = test.db.parse( source );
            test.search( doc, argv[0] );
        }
        catch( ArrayIndexOutOfBoundsException e ) {
            System.err.println( "Usage:java pattern filename" );
        }
        catch( Exception e ) {
            System.err.println( e.toString() );
        }
    }
}