Ozrix
Ozrix

Reputation: 3515

Get a node's attribute value in Xpath

I have a XML data structure that looks like this

<menu>
   <sport id="1580" name="Foo" />
   <sport id="1581" name="Bar" />
   ...

In XSL, I need to select the appropriate <sport> node via the id attribute and print out the name attribute. I'm selecting the node via this expression

{document('foo.xml')/menu/sport[@id = $id]

which works just fine, but can't figure out how to get the name attribute on the same element. Doing

{document('odkazy.xml')/menu/sport[@id = $id]/@name

doesn't work.

Upvotes: 0

Views: 225

Answers (2)

Mathias M&#252;ller
Mathias M&#252;ller

Reputation: 22617

Remove the trailing curly bracket at the beginning of your XPath expression. Change

<xsl:value-of select="{document('odkazy.xml')/menu/sport[@id = $id]/@name"/>

to

<xsl:value-of select="document('odkazy.xml')/menu/sport[@id = $id]/@name"/>

Curly brackets can be used in XSLT, too. But they denote an attribute value template:

<element name="{document('odkazy.xml')/menu/sport[@id = $id]/@name}"/>

This is the relevant part of the XSLT specification that explains attribute value templates.

Upvotes: 2

Jonathan Spickernell
Jonathan Spickernell

Reputation: 162

Could you not set a variable to the id, or even a for-each, to set you to the correct sport. and then just output the name;

<xsl:variable name="sportName" select="document('odkazy.xml')/menu/sport[@id = $id]" />
<xsl:value-of select ="$sportName/@name"/>

Not sure how well the below would work but worth a try maybe?

<xsl:for-each select="document('odkazy.xml')/menu/sport[@id = $id]">
<xsl:value-of select ="@name"/>
</xsl:for-each/>

May all be nonsense as i can't really see why

<xsl:value-of select="document('odkazy.xml')/menu/sport[@id = $id]/@name"/>

would not work

Upvotes: 0

Related Questions