RE: [xsl] Problem for : increment a variable in a for-each?

Subject: RE: [xsl] Problem for : increment a variable in a for-each?
From: "Andrew Welch" <ajwelch@xxxxxxxxxxxxxxx>
Date: Fri, 26 Nov 2004 08:28:48 -0000
> I found several people asked the same question with me
> "Re: [xsl] how to increment a variable in a for-each
> loop" but it really didn't resolve my problems. So
> just wonder could I get help ? I spent lots of time on
> it and can't get solution!
>
> My xml file
> <root>
> <list>
>     <ID>21</ID>
>    <Title>text1</Title>
>    <ParentID>1<ParentID>
> </list>
> <list>
>     <ID>22</ID>
>    <Title>text2</Title>
>    <ParentID>21<ParentID>
> </list>
>
> <list>
>     <ID>23</ID>
>    <Title>text3</Title>
>    <ParentID>21<ParentID>
> </list>
>
> <list>
>     <ID>24</ID>
>    <Title>text4</Title>
>    <ParentID>21<ParentID>
> </list>
>
> <list>
>     <ID>25</ID>
>    <Title>text5</Title>
>    <ParentID>1<ParentID>
> </list>
>
> </root>
>
> What I want do: I need do different thing  for the
> node which  parentID is 21(by passing in )(exampel:If
> it is first child then I need bold. if not first and
> not last one then I need do second thing. If the node
> is last child then I need do third things.
>
> I try to use the call:template and xsl:for each to
> pass the parameter but the count is always set to
> initial since I run so many for each
> what I shoud do ?

Try the following stylesheet, hopefully it's clear enough.  A good rule
of thumb - always use templates!  If you are new to the language, using
xsl:for-each will tempt you into the wrong way of thinking, whereas
using templates forces you to understand whats going on in the
background (although it seems completely wrong to start with :)

<xsl:stylesheet version="1.0"
 xmlns:xsl="http://www.w3.org/1999/XSL/Transform";>

<xsl:param name="ID" select="'21'"/>

<xsl:template match="/">
	<xsl:apply-templates/>
</xsl:template>

<xsl:template match="list">
	<xsl:choose>
		<xsl:when test="ID = $ID and
not(preceding-sibling::list)">
			<!-- I'm equal to 21 and at the start of the
list -->
		</xsl:when>
	    <xsl:when test="ID = $ID and not(following-sibling::list)">
			<!-- I'm equal to 21 and at the end of the list
-->
	    </xsl:when>
	    <xsl:when test="ID = $ID">
			<!-- I'm equal to 21 and in the middle of the
list -->
	    </xsl:when>
	    <xsl:otherwise>
			<!-- I'm not equal to 21! -->
	    </xsl:otherwise>
	</xsl:choose>
</xsl:template>

</xsl:stylesheet>


cheers
andrew

Current Thread