tags:

views:

41

answers:

2

Hello,

I'm trying give a variable a value within XSL:for-each and access the variable after the XSL:for-loop has ended (or even after it's moved to the next XSL:for-each). I've tried using both global and local variables but they don't seem to work.

Is this possible? If not, is there another way around the problem?

-Hammer

+1  A: 

I'm trying give a variable a value within XSL:for-each and access the variable after the XSL:for-loop has ended (or even after it's moved to the next XSL:for-each)

No, this is not possible. There are ways around it, but which one is the best depends on what you want to do.

See this very similar question for a detailed explanation. Also read this thread, as it is closely related as well.

Tomalak
A: 

XSLT variables are immutable(cannot be changed) and are strictly scoped.

You can always wrap the xsl:for-each with an xsl:variable. Any text values emitted within the xsl:for-each will be assigned to the xsl:variable.

For example, the following stylesheet declares a variable textValueCSV. Within the xsl:for-each it uses xsl:value-of and xsl:text. All of the text values are assigned to the variable textValuesCSV, which is used outside of the xsl:for-each to select it's value.

<?xml version="1.0"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"&gt;

<xsl:output method="text" />

<xsl:template match="/">

    <xsl:variable name="textValuesCSV">
        <xsl:for-each select="/*/*">
            <xsl:value-of select="."/>
            <xsl:if test="position()!=last()">
                <xsl:text>,</xsl:text>
            </xsl:if>
        </xsl:for-each>
    </xsl:variable>

    <xsl:value-of select="$textValuesCSV"/>

</xsl:template>

</xsl:stylesheet>

When applied to this XML:

<doc>
    <a>1</a>
    <b>2</b>
    <c>3</c>
</doc>

Produces this output:

1,2,3
Mads Hansen