2009-11-19 66 views
3

我有例如像這樣VTD XML內的XPath表達式

<root> 
<test> 
    <bla>test1</bla> 
</test> 
<test> 
    <bla>test2</bla> 
</test> 
<test> 
</test> 
</root> 

一個XML文件,現在我想通過使用XPath表達式與VTD-XML解析器解析它。首先,我通過

VTDNav vn = vg.getNav(); 
AutoPilot ap = new AutoPilot(vn); 
ap.selectXPath("//test"); 

現在我想這個test標籤中搜索bla標籤

搜索 test標籤
int result = -1; 
int count = 0; 

while ((result = ap.evalXPath()) != -1) { 
// evaluate XPath Expressions within the test tags 
} 

誰能告訴我如何使這個表情?我不想搜索整個文檔的bla標籤,因爲我希望能夠將bla標籤分配給test標籤。例如,如果bla標籤爲空,我無法執行此操作,並且我在整個文檔中搜索bla標籤。

回答

3

你可以聲明另一個自動駕駛儀(如下圖所示),但它並不總是最簡單的方法

AutoPilot ap2 = new AutoPilot(); ap2.selectXPath("blah"); 

然後窩在循環

while ((result = ap.evalXPath()) != -1) { 
// evaluate XPath Expressions within the test tags 
    int i2=-1; 
    while((i2=ap2.evalXPath())!=-1){ 
    // do more stuff here 
    } 
} 

但美中不足的是,在第二個XPath需要相對xpath表達式...

+0

此方法是否可以提高CPU週期的性能? – 2012-06-21 03:39:00

+0

嗨,不要忘了使用nv.push和nv.pop來跟上當前的光標位置,這裏有一個例子http://www.codeproject.com/Articles/28237/Programming-XPath-with-VTD- XML – Nei 2013-01-01 19:28:27

2

初始段似乎表明,你想這樣的:

//test/bla 

然而,結束段似乎表明你想要的東西不同。

1

這是使用2個xpath的替代方案。只需使用一個xpath即可獲取「測試」標籤,然後使用一個循環遍歷其尋找「bla」標籤的子項。

VTDNav vn = vg.getNav(); 
AutoPilot ap = new AutoPilot(vn); 
ap.selectXPath("//test"); 

while (ap.evalXPath() != -1) { 
    System.out.println("Inside Test tag"); 

    //now find the children called "bla" 
    if(vn.toElement(VTDNav.FIRST_CHILD, "bla")){ 
    do{ 
     int val = vn.getText() ; 
     if(val!=-1){ 
     String value = vn.toNormalizedString(val); 
     System.out.println("\tFound bla: " + value); 
     } 
    } 
    while(vn.toElement(VTDNav.NEXT_SIBLING, "bla")); 
    } 
    //move back to parent 
    vn.toElement(VTDNav.PARENT); 
}