簡體   English   中英

xPath評估為節點返回null,但是count()函數顯示有值

[英]xPath evaluation returns null for node, but count() function shows that there are values

我在計算為一個特定的xpath獲得的節點數,然后遍歷這些節點。

對於特定的xpath,計數為6。前4個節點帶有值。 當我到達第五和第六時,我得到零。

XML大致如下所示

<account>
    <contact>
    <contact>
    <contact>
    <contact>
</account>
<account>
    <contact>
    <contact>
</account>

這是一個代碼片段:

String count = xpath.evaluate("count("+genericPath+")", LegacyXML);
                  System.out.println("count " +count);


                  for (int a = 1; a <= Integer.valueOf(count); a++){
                      XPathExpression genPath = xpath.compile(genericPath+"["+a+"]");
                      Object result = genPath.evaluate(LegacyXML, XPathConstants.NODE);
                      Node nodes = (Node) result; 

                      Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
                      try{
                          doc.appendChild(doc.importNode(nodes, true));
                          System.out.println("this is eval result :) "+ xpath.evaluate(genericPath+"["+a+"]", LegacyXML).toString());

                      }catch(NullPointerException e){
                          System.out.println("Please ensure that the hierarchy code of" +PKattribute+ " in " +LegacyAPI + " is correct. It doesn't point to an array.");
                          System.out.println("this is eval result :( "+ xpath.evaluate(genericPath+"["+a+"]", LegacyXML).toString());



  }

所以我正確地獲得了前四個節點,后兩個為空。 當我打開XML並查看它時,顯然存在值。 在各種在線xPath評估中測試變量'genericPath'將返回具有值的6個節點。 我想念什么?

任何幫助,將不勝感激。

編輯:genericPath = // *聯系人

如果通用路徑是//contact則它將選擇6個元素。

//contact[N]選擇作為其父級的第N個子級的每個聯系人。 因此//contact[5]//contact[6]什么也不選擇。

您想要(//contact)[N]

重復使用字符串連接構造這樣的表達式效率極低。 像這樣解析和編譯XPath表達式可能要花費執行它100倍的時間。 用可以在運行時提供的參數編譯單個表達式要好得多。 甚至更好的是,求一個返回所有六個元素的表達式。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM