DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Jimmy has posted 14 posts at DZone. View Full User Profile

How To Use XPath And Namespaces In VTD-XML?

11.29.2009
| 5845 views |
  • submit to reddit
        This example shows you how to use XPath to process an XML document in a namespace aware fashion.

/* Input XML 
<ns1:a xmlns:ns1="someURL">
	<ns1:b> hello world! </ns1:b>
</ns1:a>
*/
import com.ximpleware.*; 
public class xpathNs{
        public static void main(String[] args) throws Exception{
            VTDGen vg = new VTDGen();
            AutoPilot ap = new AutoPilot();
            int i;
            // declareXPathNameSpace associates name space with a prefix
            ap.declareXPathNameSpace("ns1","someURL");
	    ap.selectXPath("/ns1:a/ns1:b/text()");
            if (vg.parseFile("d:/java_tutorial_by_code_examples/3/input.xml",true)){
                VTDNav vn = vg.getNav();
                ap.bind(vn); 
                // AutoPilot moves the cursor for you, as it returns the index value of the qualified node
                while((i=ap.evalXPath())!=-1){
                    // notice that i always is equal to vn.getCurrentIndex()!!!
                    System.out.println("the text node index val is "+ 
                        i +" the text string ==>"+vn.toString(i));
                    // below is equivalent to 
                    // vn's cursor is what gets moved by AutoPilot here
                    System.out.println("the text node index val is " + 
                        i + " the text string ==>" + vn.toString(vn.getCurrentIndex()));
                }
            }
        } 
}