2011-09-02 79 views
2

我想要計算某個節點的所有後代或自己的節點,但只有所有的後代都低於某個從0開始的後代。您是否有任何建議?XPath查詢幫助(計數)

基本上它看起來是這樣的:

count(//fstructure/node()) + count(//fstructure/node()/node()) + count(//fstructure/node()/node()/node()) + 1 

作品3級和(元素)節點「fstructure」,即使它不是真的很好,但我只需要它來完成調試。

問候,
約翰內斯

+0

提供樣本e XML。 –

+0

也許這是一個糟糕的XPath查詢,但我希望它不正確:count(// fstructure/node())+ count(// fstructure/node()/ node())+ count(// fsctruture/node ()/ node()/ node())+ 1,假設我想從元素節點「fstructure」開始計數3個級別。 – Johannes

+0

好吧,它似乎是正確的(儘管我的拼寫錯誤),但也許不是最好的方式來做到這一點。 – Johannes

回答

2

此XPath表達式

count(
    ExprForYourNode//* 
        [not(count(ancestor::*) 
         > 
         count(ExprForYourNode/ancestor::*) + 2 
         ) 
        ] 
     ) 

選擇所有後代或自元件關閉由表達式ExprForYourNode具有2最大深度選擇的元素(零基)

如果你wan噸選擇所有後代或自節點(元素,文本節點,註釋節點和處理指令節點)使用

count(
    ExprForYourNode//node() 
        [not(count(ancestor::*) 
         > 
          count(ExprForYourNode/ancestor::*) + 2 
         ) 
        ] 
     ) 

例如與此文檔

<t> 
<a> 
    <b> 
    <c> 
     <d/> 
    </c> 
    </b> 
</a> 
</t> 

這個表達式

count(
    /*/a//* 
      [not(count(ancestor::*) 
       > 
       count(/*/a/ancestor::*) + 2 
       ) 
      ] 
     ) 

產生

2 

這是與相對深度的a後代到a 2或更少的元件的數目(bc,但不是d)。

類似地,本表達的評價:

count(
    /*/a//node() 
      [not(count(ancestor::*) 
       > 
       count(/*/a/ancestor::*) + 2 
       ) 
      ] 
     ) 

產生

6 

即元素的數量(如前)加的數量(空白 - 僅)文本節點深度最多2個元素a

+1

太棒了,甚至沒有想過算上祖先;-) – Johannes

+0

@Johannes:不客氣。 –