2

i have an xml file like this.

<a>
    <b>
        <c>
            <d>Text</d>
        </c>
        <c>
            <d>Text</d>
        </c>
    </b>
    <b>
        <c>
            <d>Text</d>
        </c>
        <c>
            <d>Text</d>
        </c>
    </b>
</a>

I'm in <d> node and i need to get the number of <c> node inside <b>. Be aware that this is just a sample so we can have deeper structure and <c> will not be direct parent of <d>. So, what i need. I need to have in first <d> node 1 (because we inside <c> and it is first in <b>) in the second 2, in third 1 and in fourth 2. We don't need to count all <c> elements but only parents of current <d> inside parent <b>.

For now i have count(preceding::c) . But it counts all 4 <c> nods.

Please help. Thank you.

P.S. I'm using xsl 1.0

4

2 回答 2

2

I need to have in first <d> node 1 (because we inside <c> and it is first in <b>)

So you need to go up the tree to the current node's c ancestor and then count the number of that element's preceding c siblings:

count(ancestor::c[1]/preceding-sibling::c) + 1

The +1 is because the first c in a given b will have no preceding siblings, the second will have one, etc.

To ensure you go up the tree to the c that is a child of b (e.g. if there may be other elements named c in between) you can be more specific

count(ancestor::c[parent::b][1]/preceding-sibling::c) + 1

to target only a c that itself has a b as its parent.

于 2013-11-08T08:44:28.570 回答
1

只需转到您想去的级别并数孩子。

count(../../c)

或者

count(ancestor::b[1]/c)
于 2013-11-08T08:32:38.867 回答