XSL: Count levels between current node and another specific node

143 views Asked by At

I have following XML structure:

<someSubNodeInXmlFile text="mainListStart">
    <a text="text1">
        <b text="text2">
            <a text="text3">
                <c text=""text4/>
            </a>
            <a text="text5"/>
        </b>
    </a>
    <a text="text6">
        <c text="text7"/>
    </a>
</someSubNodeInXmlFile>

My problem is about numbering. The above XML can be seen as a nested list.

The default format for the numbering is '1.1.1 ', level="multiple". But if the list is nested for the 4th time or more, the format should change to '1', level="single".

The desired output for the above structure would be:

1. mainListStart
    1.1 text1
        1.1.1 text2
            1   text3
                1   text4
            2   text5
    1.2 text6
        1.2.1 text7

In my opinion e.g. if my current node is the first I need to calculate how many ancestors are between my current node and the parent . If the calculated number is lower than 4, use '1.1.1 ' as list-item format, otherwise use '1' as format.

I tried several things now, but none of them worked. I am able to calculate how many ancestors in general I have for the current node, but this is calculating the complete ancestor tree, and not until the specific node 'someSubNodeInXmlFile'.

Is this possible with a simple xpath expression or do I try to calculate the number with a recursive template that starts from current() and looks for each next ancestor if it's desired one, adding one to a number if not and proceed to the next ancestor?

I can imagine that the latter idea is not very performant (if it works at all). But what's the best solution?

Thanks in advance.

BRgrds, Jens

1

There are 1 answers

1
choroba On BEST ANSWER

If you know hot to get the number of all the ancestors of a node, then just subtract the number of the ancestors of someSubNodeInXmlFile and you have the number of the nodes in between (plus one).

R---o---o---X---o---o---o---o---o---N
            3                       9
            \_______________________/
                  9 - 3 - 1 = 5