views:

355

answers:

4

I have a xsl file that is grabbing variables from xml and they seem to not be able to see each other. I know it is a scope issue, I just do not know what I am doing wrong.

<xsl:template match="one">
 <xsl:variable name="varOne" select="@count" />
</xsl:template>

<xsl:template match="two">
 <xsl:if test="$varOne = 'Y'">
     <xsl:value-of select="varTwo"/>
 </xsl:if>
</xsl:template>

This has been simplified for here.

Any help is appreciated.

+2  A: 

I'm fairly certain that variables are scoped and therefore you can't declare a variable in one and then use it in the other. You're going to have to move your variable declaration out of the template so that it's in a higher scope than both of them.

Orion Adrian
+2  A: 

Remembering that xsl variables are immutable...

<!-- You may want to use absolute path -->
<xsl:variable name="varOne" select="one/@count" />

<xsl:template match="one">
<!-- // do something --> 
</xsl:template>

<xsl:template match="two">
 <xsl:if test="$varOne = 'Y'">
     <xsl:value-of select="varTwo"/>
 </xsl:if>
</xsl:template>
Swati
Immutable is probably a better term than static final.
Kev
+2  A: 

You may also solve some scoping issues by passing parameters...

<xsl:apply-templates select="two">
 <xsl:with-param name="varOne">
  <xsl:value-of select="one/@count"/>
 </xsl:with-param>
</xsl:apply-templates>

<xsl:template match="two">
 <xsl:param name="varOne"/>
 <xsl:if test="$varOne = 'Y'">
     <xsl:value-of select="varTwo"/>
 </xsl:if>
</xsl:template>
dacracot
+2  A: 

The scope of a variable in XSLT is its enclosing element. To make a variable visible to multiple elements, its declaration has to be at the same level or higher than those elements.

Robert Rossney