Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

variables

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.

like image 957
Jagath Jayasinghe Avatar asked May 13 '13 16:05

Jagath Jayasinghe


People also ask

How do you declare a variable and assign value in XSLT?

XSLT <xsl:variable>The <xsl:variable> element is used to declare a local or global variable. Note: The variable is global if it's declared as a top-level element, and local if it's declared within a template. Note: Once you have set a variable's value, you cannot change or modify that value!

How do you declare a variable in XSLT?

XSLT variable is defined as special tags used to declare a local or global variable that we make use of to store any values. The declared variables are referenced within an Xpath expression. Once it is set we cannot overwrite or update the variables. The scope of the element is done by the element that contains it.

How do you add two variables in XSLT?

You use the <xsl:variable> element to declare a variable and assign a value to it. Remember that these two must always be done at the same time in XSLT, you can't declare a variable and later assign it a value.

What is difference between param and variable in XSLT?

The content model of both elements is the same. The way these elements declare variables is the same. However, the value of the variable declared using <xsl:param> is only a default that can be changed with the <xsl:with-param> element, while the <xsl:variable> value cannot be changed.


1 Answers

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.

like image 185
Martin Honnen Avatar answered Sep 26 '22 16:09

Martin Honnen