tags:

views:

78

answers:

3

I can't find a reason why the following does not work.

If I have a document that looks like

<mydocroot>
<request>
   <key>Ham</key>
</request>
<node>
   <data alias='Ham' id='27'>Some value</data>
   <data alias='Eggs' id='14'>Greenish</data>
   <data alias='Condiment' id='32'>Salt and pepper</data>
   ...
</node>
</mydocroot>

and an xsl template that looks like

<xsl:template match="/">
    <xsl:value-of select="/mydocroot/node/data[@alias=string(/mydocroot/request/key)]" />
</xsl:template>

prints nothing.

<xsl:template match="/">
    <xsl:value-of select="/mydocroot/node/data[@alias='Ham']" />
</xsl:template>

prints "Some value" as expected.

What am I doing wrong?

Thanks!

Edit:

I'm actually not 100% positive what the underlying document I'm working with looks like, but I do know that, to continue with this example,

<xsl:value-of select="/mydocroot/request/key" /> <!-- prints "Ham" -->

works.

Should I be able to match an attribute value to a node value?

A: 

If you start an XPath expression using a "/", it indicates that you are starting from the root node of the document, but the root element is "mydocroot", so you need to include that in your XPath.

<xsl:value-of select="/mydocroot/node/data[@alias=string(/mydocroot/request/key)]" />
Thiyagaraj
Wouldn't he need to include /xml also before "node"? And shouldn't that omission make his second template fail?
Martin v. Löwis
@Martin Thanks, My bad, I didnt notice that the requestor also changed the leading selector, corrected it.
Thiyagaraj
Oops, requestor changed info in the question, updated again
Thiyagaraj
A: 

So I got the following to work, but it seems hackish:

<xsl:template match="/">
    <xsl:variable name="aliasval"><xsl:value-of select="string(/mydocroot/request/key)" /></xslvariable>
    <xsl:value-of select="/myrootdoc/node/data[@alias=$aliasval]" />
</xsl:template>

Should I be required to create a variable just for this? I'm probably bumping up against my knowledge of XSLT here.

Jason Denizac
Look at my other solution, why not just have the XPath in your selector instead of putting it in a variable and then using that.
Thiyagaraj
A: 

"Should I be able to match an attribute value to a node value?"

Definitively yes. An attribute value is a string, and when comparing against a string, XSLT coerces the other operand to a string automatically. No need to call string() explicitly. This works for me (and it should work for you as well):

<xsl:value-of select="/mydocroot/node/data[@alias = /mydocroot/request/key]" />
<!-- prints "Some value" -->

Better, because more explicit (/mydocroot/request/key could select more than one node!):

<xsl:value-of select="/mydocroot/node/data[@alias = /mydocroot/request/key[1]]" />

In these siutations, an <xsl:key> also would come in handy:

<xsl:key name="kDataByAlias" match="node/data" use="@alias" />

<!-- later... -->

<xsl:value-of select="key('kDataByAlias', /mydocroot/request/key[1])" />
Tomalak