Reputation: 329
The code outputs the "url" for every "image" ok (up the the limit of 8) with $sep after each url.
But I want to setup a condition that if it finds eg 4 "image" then it will output $sep 4 times (after printing out 4 urls with $sep after each one). But when I tried the code below it does not seem to be counting the image/images as the count is always 1 (no matter how many "images" there are).
Example xml input
<images>
<image>
<url>Url</url>
</image>
<image>
<url>Url</url>
</image>
<image>
<url>Url</url>
</image>
<image>
<url>Url</url>
</image>
</images>
XSL code
<xsl:for-each select="images/image[position() <= 8]">
<xsl:value-of select="url"/> <xsl:value-of select="$sep" />
</xsl:for-each>
<xsl:variable name="set" select="images/image" />
<xsl:variable name="count" select="count($set)" />
<xsl:choose>
<xsl:when test="count='4'">
<xsl:value-of select="$sep" />
<xsl:value-of select="$sep" />
<xsl:value-of select="$sep" />
<xsl:value-of select="$sep" />
</xsl:when>
</xsl:choose>
current output
URl,URl,URl,URl,
wanted output
URl,URl,URl,URl,,,,,
Thanks
Upvotes: 0
Views: 627
Reputation: 70618
You have missed off the $
sign when checking the count
variable. It should be this...
<xsl:when test="$count=4">
(No need for apostrophes around the 4 either, as $count is a number, although it should still work in XSLT 1.0)
EDIT: Consider using a recursive template to cope with any number of image
elements in your XSLT.
Try this..
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="2.0">
<xsl:output method="text" />
<xsl:variable name="sep" select="','" />
<xsl:template match="/">
<xsl:for-each select="images/image[position() <= 8]">
<xsl:value-of select="url"/> <xsl:value-of select="$sep" />
</xsl:for-each>
<xsl:variable name="set" select="images/image" />
<xsl:variable name="count" select="count($set)" />
<xsl:call-template name="pad">
<xsl:with-param name="count" select="$count" />
</xsl:call-template>
</xsl:template>
<xsl:template name="pad">
<xsl:param name="count" />
<xsl:if test="$count + 1 < 8">
<xsl:value-of select="$sep" />
<xsl:call-template name="pad">
<xsl:with-param name="count" select="$count + 1" />
</xsl:call-template>
</xsl:if>
</xsl:template>
</xsl:stylesheet>
Upvotes: 1