I am learning xslt and had one question about how can i use xslt variable in diff. for each loop. I know xslt isn’t a procedural language so variable declared in for loop cannot be accessed in another loop. But is there any way I can just declare global variable then assign some value in first for loop and use that variable in second for loop?
Any ideas would be highly appreciated.
Thanks
The way to assign value to an
xsl:variable(of course this is only initialization) from within anxsl:for-each, is to include thexsl:for-eachin the body of the variable.Here is a complete example:
When this transformation is applied on the following XML document…
…it first defines a
vMaxvariable that gets its value from thexsl:for-eachcontained in its body.Then the
vMaxvariable is used in the secondxsl:for-eachto output all numbers that are “close” to the so computed maximum.The wanted, correct result is produced:
It is also possible to simulate “assigning” a variable with different values by using a recursively called named template and pass the “new value” as parameter to the called template.
Here is an example showing this technique. Here we are calculating the maximum of values, contained in nodes of a node-set. Every time we access the next node in the node-set, the current maximum is compared to this value and if necessary the new maximum becomes the value of the next node. We then call the same template recursively, passing as the value of the current maximum the new maximum:
When this transformation is applied to the same XML document (above), the wanted, correct result is produced: