Friday 18 May 2012

count preceding siblings in a flat structure

If there was a degree in the bleeding obvious I swear I would fail it.
A recent need to create an xpath to find the number of preceding siblings from a specific point in those preceding siblings was perplexing me. The xml was something like:
<items>
    <item/>
    <item/>
    <item/>
    <item/>
    <item marker="true"/>
    <item/>
    <item/>
    <item/>
    <item/>
    <item/>
    <item/>
    <item/>
    <item/>
    <item/>
    <item/>
    <item/>
</items>
What was needed was an xpath to calculate how many preceding siblings an item element was from the item element with the marker attribute. After playing around a little, I came up with:
count(preceding-sibling::*[preceding-sibling::*/generate-id() = current()/preceding-sibling::*[@marker = 'true'][1]/generate-id()])
which worked a treat but was rather over-wieldy. It wasn't until looking at this from an Arbortext Styler persepective which refused to accept the current() and generate-id() functions (probably because these are xslt only functions rather than true xpath functions) that the bleeding obvious poked its head up and whacked me around the chops with a proverbial wet fish.
count(preceding-sibling::*) - count(preceding-sibling::*[@marker='true'][1]/preceding-sibling::*)
simple when you think about it!