1

how can I refer to the current node matched by a template, within a for-each loop.

<xsl:template match="product[@category='foo']">
    <count>
        <xsl:for-each select="preceding::product">
                <current>
                    <xsl:value-of select="count(current()/preceding::product)"/>
                </current>
                <context>
                    <xsl:value-of select="count(./preceding::product)"/>
                </context>
        </xsl:for-each>
    </count>
</xsl:template>

Both count() functions return the same results with . as well as current().

Is there a way to refer to the matched node of the template, in order to count all the preceding nodes of it, so that the result of the count() function inside <current/> is the same for every for-each step.

Thanks!

FelHa
  • 1,043
  • 11
  • 24

1 Answers1

3

Put the current node in a variable....

<xsl:template match="product[@category='foo']">
    <xsl:variable name="current" select="." />
    <count>
        <xsl:for-each select="preceding::product">
                <current>
                    <xsl:value-of select="count($current/preceding::product)"/>
                </current>
                <context>
                    <xsl:value-of select="count(./preceding::product)"/>
                </context>
        </xsl:for-each>
    </count>
</xsl:template>

In this example though, you would be better place putting the results of the count in a variable though...

Put the current node in a variable....

<xsl:template match="product[@category='foo']">
    <xsl:variable name="count" select="count(preceding::product)" />
    <count>
        <xsl:for-each select="preceding::product">
                <current>
                    <xsl:value-of select="$count"/>
                </current>
                <context>
                    <xsl:value-of select="count(./preceding::product)"/>
                </context>
        </xsl:for-each>
    </count>
</xsl:template>
Tim C
  • 70,053
  • 14
  • 74
  • 93
  • Thanks! So the difference between current and context only matters within a neseted XPath-Expression? – FelHa Mar 21 '18 at 15:14
  • See https://stackoverflow.com/questions/1022345/current-node-vs-context-node-in-xslt-xpath – Tim C Mar 21 '18 at 15:15