2017-04-03 75 views
0

我有一個相當深的嵌套xml結構,我想在選擇節點後找到具有特定值的元素。在下面的示例中,我有一個'B'數組,並且在選擇每個'B'節點後,我想要獲取以「歷史記錄」開頭的其中一個子節點(不一致)的文本XPath在節點選擇中查找帶有文本()的任何元素

<A> 
    <Items> 
     <B> 
      <C> 
       <D>history: pressed K,E</D> // could be nested anywhere 
      </C> 
     </B> 
     <B> 
      <C> 
       <E>history: pressed W</E> 
      </C> 
     </B> 
    </Items> 
</A> 


    // Select the nodes from the array (B) 
var nodes = select(xmldoc, "//A/Items/B"); 

    // Iterate through the nodes. 
nodes.forEach(node){ 

    // is it possible to select any element that starts with the text 'history' from the already selected node. 
var history = select(node, "???[starts-with(.,'history')]"); 

我看到的所有樣本都是從// * [text()]開始,從結構的根部搜索。

回答

0
//B//*[starts-with(normalize-space(), 'history')] 

看起來像它會做你想要的。

它選擇<B>的任何後代元素,其文本內容以'history'開頭」

手動迭代尋找更多節點通常不是必需的。 XPath爲您做到了這一點。如果由於其他原因必須進行迭代,請使用上下文節點.進行選擇。

nodes.forEach(function (node) { 
    var history = select(node, "./*[starts-with(.,'history')]"); 
}); 

如果你實際上是在尋找「任何文本節點...」

//B//text()[starts-with(normalize-space(), 'history')] 

或者「有沒有進一步的子元素的任何元素節點...」

//B//*[not(*) and starts-with(normalize-space(), 'history')] 
+0

不幸的是,這仍然返回2結果,而不是結果的se節點。這是因爲我們從擁有多個記錄的// B開始。 – Celica

+0

類似這樣的工作: select(node,「C/*/[starts-with(normalize-space(。),'history')]」); 所以它會從元素中選擇。 *在當前級別搜索所有的孩子,它不搜索孩子的孩子,這是有道理的。 我實際上正在尋找一種方法來完成當前節點的全部搜索和所有孩子。 – Celica

相關問題