I would have thought this would be an easy one to Google, but I've been unsucessful.
I want to assign a variable the value out of an attribute (easy so far) then use that variable to select another node based on the value of that attribute.
Example:
<xsl:variable name="myId" select="@id" />
<xsl value-of select="//Root/Some/Other/Path/Where[@id='{@myId}']/@Name />
That does not work. If I replace the {@myId} with the value that is in the variable then it does find the right node, but doign it this way produces nothing. I'm sure I'm missing something, or perhaps there is a different way to do it.
The context is that there is related data under different top-level nodes that share the same id value so I need to get the related nodes in my template.
Definition and UsageThe <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!
XSLT current() Function Usually the current node and the context node are the same. However, there is one difference. Look at the following XPath expression: "catalog/cd". This expression selects the <catalog> child nodes of the current node, and then it selects the <cd> child nodes of the <catalog> nodes.
I second @scunliffe - if $var exists but is empty, test="$var" will still return true. However, you may need to write it test="not($var = '')" if you are using earlier versions of XSL.
Ok, I finally figured it out. Silly problem really, I simply needed to leave out the quotes and the braces. One of those times when I thought that I'd already tried that. :D Oh, and I mistyped @myId in the first example, the code was actually $myId.
<xsl:variable name="myId" select="@id" />
<xsl value-of select="//Root/Some/Other/Path/Where[@id=$myId]/@Name" />
You seem to have got confused with use of a variable (which is just $variable) and Attribute Value Templates, which allow you to put any XPath expression in some attributes, e.g.
<newElement Id="{@Id}"/>
They can obviously be combined, so you can include a variable in an Attribute Value Template, such as:
<newElement Id="{$myId}"/>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With