开发者

Help with XPath query (count)

开发者 https://www.devze.com 2023-04-01 19:43 出处:网络
I want to count all descendant-or-self nodes of a certain node, but just all descendants which are lower than a certain level starting at 0. Do you have any suggestions?

I want to count all descendant-or-self nodes of a certain node, but just all descendants which are lower than a certain level starting at 0. Do you have any suggestions?

Basically it seems something like:

count(//fstructu开发者_开发技巧re/node()) + count(//fstructure/node()/node()) + count(//fstructure/node()/node()/node()) + 1

works for 3 levels and the (element) node "fstructure", even if it's not really nice, but I just needed it for debugging.

best regards,

Johannes


This XPath expression:

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

select all descendent-or-self elements off the element selected by the expression ExprForYourNode with maximum depth of 2 (zero based)

If you want to select all descendent-or self nodes (elements, text-nodes, comment-nodes and processing-instruction-nodes) use:

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

For example with this document:

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

this expression:

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

produces:

2

This is the number of elements (b and c, but not d) that are descendents of a with relative depth to a 2 or less.

Similarly, the evaluation of this expression:

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

produces:

6

That is the number of elements (as before) plus the number of (white-space-only) text nodes at depth up to 2 relative the element a

0

精彩评论

暂无评论...
验证码 换一张
取 消