Re: [xsl] simulating for with foreach

Subject: Re: [xsl] simulating for with foreach
From: David Carlisle <davidc@xxxxxxxxx>
Date: Wed, 5 Jul 2006 11:54:56 +0100
> Do I have to use <xsl:if test="position() mod 4 = 1", or there is
> a more flexible way?

It depends what you mean by flexible. Using that method you can use any
sequence that may be expressed by an Xpath formula, which is pretty
flexible, but if your sequence isn't expressed by formula, or has
repeated numbers and is perhaps from some empirical sampled data and you
need something like
1 32 2 5 7 2 4 7

just list them in some document

list.xml
<list>
<n>1</n> <n>32</n> <n>2</n> <n>5</n> <n>7</n> <n>2</n> <n>4</n> <n>7</n
</list>

and then do

<xsl:variable name="nodes" select="node"/>
<xsl:for-each select="document('list.xml')/list/n">
<xsl:for-each select="$nodes[position()=current()]">
.
</xsl:for-each>
</xsl:for-each>

If you have an extension function like saxon:tokenize you can avoid the
explict document

<xsl:variable name="nodes" select="node"/>
<xsl:for-each select="saxon:tokenize('1 32 2 5 7 2 4 7')">
<xsl:for-each select="$nodes[position()=current()]">
.
</xsl:for-each>
</xsl:for-each>

If you have XSLT2 you can avoid the extension function

<xsl:variable name="nodes" select="node"/>
<xsl:for-each select="1,32,2,5,7,2,4,7">
<xsl:for-each select="$nodes[position()=current()]">
.
</xsl:for-each>
</xsl:for-each>

David

Current Thread