XSLT following-sibling
Contrary to what you might instinctivley believe, using the following-sibbling:: axis in XSLT does not give you the following sibling. It does in fact give you all the following siblings!
We can prove this be looking at an example. Suppose we have the following xml document:
We will now transform this with some xslt which will attempt to select all People who have a following sibling of Will. Now if this was to evaluate to just the 1 following sibling then we would expect to see just Tiffany. The results we actually get though are Dave Fred And Tiffany. Here is our XSLT:
This gives us the following results:
Dave<br /><br /> Fred<br /><br /> Tiffany<br /><br />
So this proves that following sibling gives us all following siblings, not just the next one.
Important!
Now the above example also shows something very important. When we use the = operator with a collection of nodes it returns true if the single entity exists anywhere within the collection which of course makes sense if you back and look at the results of the previous example. We can also prove this with the following experiment,
The above transformation gives us the following results proving the theory on how = works:
Experiment
Tiffany exists in PepolePeople are as follows
Dave
Fred
Tiffany
Will
Hilary
Fred
It is of course possible to specify just the preceeding sibling - by using an index. If we change our template code as follows:
Then we just get Tiffany as our output. If we changed it to 2 we would get Fred and 3 would give us Dave. We can see therefore that the index collection (for want of a better expression) is like an array with the items in order of proximity to the original node. You can test this by performing the mirror image function and using preceding-sibling as follows:
<xsl:template match="//Person[preceding-sibling::Person/Firstname = 'Fred']">
<xsl:value-of select="Firstname"></xsl:value-of><br /><br />
</xsl:template>
In laymans terms this is saying select all People whose preceding person is Fred. This should and does give us Tiffany, Will and Hilary. Now to test our array proximity theory we should get 1 for Tiffany, 2 for Will and 3 for Hilary. You can try this yourself and see that it does work.
One other point really worth noting is that we have to specify what the sibling is ie we had to but the word Person after the ::