XPathTest2.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 XPathTest2 {

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

  /** Constructor */
    public XPathTest2() {
        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( toAbsolutePath(n) );
            }
        }
        catch( TransformerException e ) {
            System.err.println( "Pattern not correct" );
        }
        catch( Exception e ) {
            System.err.println( e.toString() );
        }
    }

  /** convert to absolute path */
    private String toAbsolutePath( Node node ) {

         String myname = node.getNodeName();
         StringBuffer sb
            = new StringBuffer( "<" + myname + ">" );
         Node owner = node.getOwnerDocument();
         Node parent = node.getParentNode();
         while( parent != owner ) {
             String pname = parent.getNodeName();
             sb.insert( 0, "<" + pname + ">" );
             parent = parent.getParentNode();
         }
         return sb.toString();
    }

  /** start here */
    public static void main( String[] argv ) {
        try {
            XPathTest2 test = new XPathTest2();
            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() );
        }
    }
}