从VTD XML中的元素计算XPath表达式

时间:2012-12-17 11:19:06

标签: vtd-xml

XML文件:

<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代码:

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

我可以存储app元素并在app元素中执行xpath表达式。喜欢这个

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

如何在VTD XML中执行此操作?

1 个答案:

答案 0 :(得分:1)

我认为您可以通过访问VTD-XML的sourceforge网站来学习API。以下是我认为它的样子:

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
    }


}