xsl-list
[Top] [All Lists]

Re: [xsl] Hello - how do I use the count function properly?

2010-09-17 16:12:39

And on every 4th subcategory I just want to set the margin-
right: 0px.

Here is the XSL and my attempt.

Please guide me.

  <xsl:template match="category">
   <xsl:for-each select="child::category">
    <xsl:choose>
     <xsl:when test="count(/child::category)=4 or
count(/child::category)=8">

There are several significant problems with this code.

First, xsl:for-each sets the context node, and any path expression immediately within the for-each selects using that context node as its start point. If you wrote "child::category" or "./child::category", you would be testing whether the category node you are currently processing has 4 (or 8) children called category, whereas you actually want to test whether it has 3 (or 7) preceding siblings called category.

Secondly, by writing /child:category, you are not selecting children of the context node, but children of the root (document) node at the top of the tree. (A document node in a well-formed XML document has exactly one element child, so testing whether it has 4 or 8 children will always return false.)

You could write this as

<xsl:for-each select="child::category">
<xsl:choose>
<xsl:when test="count(preceding-sibling::category) = 3 or count(preceding-sibling::category) = 7"

but I would tend to write it as

<xsl:for-each select="child::category">
<xsl:choose>
<xsl:when test="position() mod 4 = 0" ...

The position() function returns 1, 2, 3, ,,, in successive executions of the xsl:for-each body.

Michael Kay
Saxonica

--~------------------------------------------------------------------
XSL-List info and archive:  http://www.mulberrytech.com/xsl/xsl-list
To unsubscribe, go to: http://lists.mulberrytech.com/xsl-list/
or e-mail: <mailto:xsl-list-unsubscribe(_at_)lists(_dot_)mulberrytech(_dot_)com>
--~--