Re: [xsl] A Counter Variable in XSLT?

Subject: Re: [xsl] A Counter Variable in XSLT?
From: "Thomas B. Passin" <tpassin@xxxxxxxxxxxx>
Date: Fri, 5 Oct 2001 15:34:05 -0400
OK, you didn't show us any xml, so I made some up.  Here is the XML:

<doc>
 <item col='cars'>Chevy</item>
 <item col='animals'>Lion</item>
 <item>Item with no col</item>
 <item col='cars'>Mercedes</item>
</doc>

One of the items has no collection, you notice.

Here is a stylesheet to do exactly what you said you want:

<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform";>
<xsl:output encoding='utf-8' method='html'/>

<xsl:template match='doc'>
 <html>
   <xsl:apply-templates select='item[@col]'/>
 </html>
</xsl:template>

<xsl:template match='item'>
  <match>
   Match #<xsl:value-of select='position()'/><br/>
   Collection: <xsl:value-of select='@col'/><br/>
   Content: <xsl:value-of select='.'/><br/><br/>
  </match>
</xsl:template>

</xsl:stylesheet>


Here is the result:

<html><match>
   Match #1<br>
   Collection: cars<br>
   Content: Chevy<br><br></match><match>

   Match #2<br>
   Collection: animals<br>
   Content: Lion<br><br></match><match>

   Match #3<br>
   Collection: cars<br>
   Content: Mercedes<br><br></match></html>

Here is the principle: select just the elements you want - here, item
elements that have a "col" atttribute.  Then position() gives you their
position.

If instead you looked at all item elements and used an xsl:if to process
them only if they had a "col" attribute, then position() would not work
because it would give the position of the item element within the series of
all item elements, which is not what you want.  This way, you pre-select the
ones you want using item[@col] (i.e., those items with a "col" attribute),
so position() works.

You don't need a global counter for this one!

Cheers,

Tom P

[Grant Mc Auley]

> What I want to do:
>
> My stylesheet consists of one template rule.  When there is a
> match, I want a line in the output  to say, for example, "Match #
> 123:", followed by relevant text.  Since I don't know ahead of
> time how many matches there will be in the source document,
> somehow the stylesheet needs to keep a count.  Something like:
>
> <?xml version="1.0"?>
> <xsl:stylesheet version="1.0"
> xmlns:xsl="http://www.w3.org/1999/XSL/Transform";
>   <xsl:output method="text"/>
>   <xsl:template match="/*">
> <xsl:if test="@col">
>       Match # n : <!-- n is the nth match, the thing that needs to
> be incremented -->
>       Collection: "<xsl:value-of select="@col"/>"
>       Content: <xsl:value-of select="."/>
>       </xsl:if>
>   </xsl:template>
> </xsl:stylesheet>
>



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


Current Thread