Re: [xsl] <xsl:when test="position()%2=0">

Subject: Re: [xsl] <xsl:when test="position()%2=0">
From: Andrew Watt <andrew@xxxxxxxxxxxxxx>
Date: Mon, 21 Apr 2003 16:58:14 +0100
At 17:09 21/04/2003 +0200, you wrote:
first of all i wish to thank all of you guys (and gals) for providing me with great help. now i have another query

i would like to find the position of a node whether it is odd or even, and tried to use position() mod 2, but i don't know how to do it

can anyone tell me how to find the remainder of a division or else any ideas on how to find whether a node is odd or even

Luke (or should that be Craig?),


This demonstrates what I think you are asking about.

Source:
<?xml version='1.0'?>
<Things>
<Thing>First</Thing>
<Thing>Second</Thing>
<Thing>Third</Thing>
<Thing>Fourth</Thing>
<Thing>Fifth</Thing>
<Thing>Sixth</Thing>
</Things>

Stylesheet (change version to 1.0 if you prefer)

<?xml version='1.0'?>
<xsl:stylesheet
 version="2.0"
 xmlns:xsl="http://www.w3.org/1999/XSL/Transform";
 >
<xsl:output method="xml" indent="yes" encoding="UTF-8" />

<xsl:template match="/Things">
<xsl:copy >
<xsl:apply-templates select="Thing" />
</xsl:copy>
</xsl:template>

<xsl:template match="Thing">
<xsl:choose>
<xsl:when test="position() mod 2" >
<xsl:element name="Remainder"><xsl:value-of select="position() mod 2" /></xsl:element>
<xsl:copy-of select="." />
</xsl:when>
</xsl:choose>
</xsl:template>


</xsl:stylesheet>

The stylesheet uses <xsl:when> which is what you asked for. As written it produces this result:

<?xml version="1.0" encoding="UTF-8"?>
<Things>
   <Remainder>1</Remainder>
   <Thing>First</Thing>
   <Remainder>1</Remainder>
   <Thing>Third</Thing>
   <Remainder>1</Remainder>
   <Thing>Fifth</Thing>
</Things>

As you can see the remainder for the first, third and fifth elements is 1.

If you change the <xsl:when> like this
<xsl:when test="not(position() mod 2)" >

You will get the even numbered <Thing> elements as output, with remainder showing as 0 for each.

I hope that helps.

Andrew Watt



XSL-List info and archive: http://www.mulberrytech.com/xsl/xsl-list


Current Thread