TheUltimateHack
TheUltimateHack

Reputation: 135

XSL For-each loop set variable

I know vars in XSL are more like constants in other languages and they cant be set inside of an operation. However, I need to loop through a node, evaluate a child element value and if true, set that value to a param or variable. once done, i need to pass those parms into a template. I know this isnt correct, but something like this:

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    xmlns:xs="http://www.w3.org/2001/XMLSchema"
    exclude-result-prefixes="xs"
    version="2.0">
    <xsl:template match="/">
        <xsl:for-each select="/person/address/address_line">
            <xsl:if test="type = 'local_script'">
                   <xsl:variable name="vADDRESS_LINE1" select="addressValue"/>
            </xsl:if>
        </xsl:for-each>
        <xsl:call-template name="FormatAddress">
            <xsl:with-param name="ADDRESS_LINE1" select="$vADDRESS_LINE1"></xsl:with-param>
        </xsl:call-template>
    </xsl:template>
    <xsl:template name="FormatAddress">
        <xsl:param name="ADDRESS_LINE1"></xsl:param>
            <!-- laydown formatted address in xml-->
    </xsl:template>

Upvotes: 1

Views: 1827

Answers (1)

Michael Kay
Michael Kay

Reputation: 163418

I think that what you are trying to do is to bind the variable vADDRESS_LINE1 to the addressValue value of the last addressLine that has type = 'local_script'.

The correct way to do that is

<xsl:variable name="vADDRESS_LINE1" 
  select="/person/address/address_line[type='local_script'][last()]/addressValue"/>

If there's only one address_line that satisfies the predicate then you can leave out the [last()].

Upvotes: 1

Related Questions