Re: [xsl] how to get the position of first special element?

Subject: Re: [xsl] how to get the position of first special element?
From: "Joe Fawcett" <joefawcett@xxxxxxxxxxx>
Date: Sun, 6 Jun 2004 11:53:01 +0100
----- Original Message ----- From: "Chen Yi" <chen_yi36@xxxxxxxxxxx>
To: <xsl-list@xxxxxxxxxxxxxxxxxxxxxx>
Sent: Sunday, June 06, 2004 10:06 AM
Subject: [xsl] how to get the position of first special element?



ALL,

For example,
<element>
<A/>
<B/>
<A/>
<C/>
<C/>
<D/>
</element>

I want to get the position first element whoes name is not A and B, but C & D. So it's 4 for this tree segment.
How can I write the xslt to figure out this ?


Thanks,
Chen Yi

This will do but I'm sure there's a more elegant solution:

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform";>
<xsl:template match="/">
<xsl:value-of select="count((element/*[name() = 'C' or name() = 'D'])[1]/preceding-sibling::*) + 1"/>
</xsl:template>
</xsl:stylesheet>


One trap, if there aren't any matches this will give the wrong result, you may wish to test for any matches first:
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform";>
<xsl:template match="/">
<xsl:variable name="CDnode" select="(element/*[name() = 'C' or name() = 'D'])[1]"/>
<xsl:choose>
<xsl:when test="$CDnode">
<xsl:value-of select="count($CDnode/preceding-sibling::*) + 1"/>
</xsl:when>
<xsl:otherwise>
No matches
</xsl:otherwise>
</xsl:choose>
</xsl:template>
</xsl:stylesheet>



--


Joe (MVP - xml)

Current Thread