Search code examples
vtd-xml

Evaluvate XPath expression from an element in VTD XML


XML File:

<apps>
        <app name="google">
              <branches> 
                   <branch location="us">
                       <datacenters>
                               <datacenter city="Mayes County" />
                                <datacenter city="Douglas County" />
                       </datacenters>
                   </branch>
              </branches>
        </app>
        <app name="facebook">
        </app>
</apps>

Java Code:

XPath xpath = XPathFactory.newInstance().newXPath();
Document document = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(file);
String expression = "/apps/app[name='google']";
Element element = xpath.evaluvate(expression,document.getDocumentElement();
Element app = (Element)xpath.evaluvate(expression,element,XPathConstants.NODE);

I can able to store the app element and execute the xpath expression within the app element . Like this

xpath.evaluvate("branches/branch[@location='us']",app,XPathConstants.STRING);

How can I do this in VTD XML?


Solution

  • I think you can learn the API by visiting VTD-XML's sourceforge web site. Below is what I think how it will look like:

    VTDGen vg = new VTDGen();
    String filename ="this.xml";
    if (vg.parseFile(filename, true)){
        VTDNav vn = vg.getNav();
        AutoPilot ap = new AutoPilot(vn);
        ap.selectXPath("/apps/app[name='google']");
        int i=-1;
        while((i=ap.evalXPath())!=-1){
             //do something with i, it is the node index
        }
    
    
    }