Jagath Jayasinghe
Jagath Jayasinghe

Reputation: 427

Variables in XSLT how to declare , assign value and use that variable in a different location in the same XSLT

Please consider my "A/B" xPath expression returns the following node

  <Q ID="12345">
  ----
  ----
  </Q>

This is my variable

This is how I’m trying to assign a value to my tempVariable variable

  <xsl:for-each select="A/B">
  <xsl:variable name="tempVariable"><xsl:value-of select="@ID"/></xsl:variable>
  </xsl:for-each>

And after all I’m trying to use this variable

  <xsl:if test="$tempVariable='12345'">
  ....
  ....
  </xsl:if>

but here as I understand I’m getting $tempVariable ="" which is not correct.

Can someone please tell me where I’m doing wrong or how can I do this in proper way. Thank you.

Upvotes: 7

Views: 56400

Answers (1)

Martin Honnen
Martin Honnen

Reputation: 167516

Why would a path like A/B select a Q element? If you want to use a variable you need to make sure it is in scope. The variable you show in your sample is in scope inside the xsl:for-each, after the xsl:variable element.

If you want to use the variable outside the for-each you would need to declare it outside the for-each.

However I think you can simply do

<xsl:variable name="v1" select="A/B/@ID"/>
<xsl:if test="$v1 = '12345'">..</xsl:if>

there is no need for the for-each.

Upvotes: 8

Related Questions