Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you use a variable in xsl when trying to select a node?

Tags:

xslt

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.

like image 408
palehorse Avatar asked Aug 07 '08 21:08

palehorse


People also ask

How do I use an xsl variable?

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!

What does node () do in XSLT?

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.

How do I find the value of a variable in XSLT?

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.


2 Answers

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" />
like image 83
palehorse Avatar answered Oct 28 '22 03:10

palehorse


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}"/>
like image 32
samjudson Avatar answered Oct 28 '22 02:10

samjudson