Reputation: 15189
I have a for-each I want to sort by some value. But the thing I loop over only has a key that allows a connection to the value. A simple example for a document:
<foo>
<keys>
<key id="foo"/>
<key id="bar"/>
</keys>
<things>
<thing name="foo"><desc>some description</desc></thing>
<thing name="bar"><desc>another description</desc></thing>
</things>
</foo>
And a style sheet:
<xsl:for-each select="/foo/keys/key">
<xsl:sort select="/foo/things/thing[@name=@id]"/>
<xsl:value-of select="@id"/>
</xsl:for-each>
This doesn't seem to work. @id
relates to the key
element from the loop; @name
relates to thing
from the predicate. How do I solve this? I tried assigning /foo/keys/key/@id
to a variable and use that but <sort>
must be the first element in a for-each...
Upvotes: 1
Views: 216
Reputation: 56172
Use current()
function:
<xsl:sort select="/foo/things/thing[@name = current()/@id]"/>
Reference: http://www.w3.org/TR/xslt#misc-func
XML:
<foo>
<keys>
<key id="1"/>
<key id="2"/>
<key id="3"/>
<key id="4"/>
</keys>
<things>
<thing name="2">
<desc>a</desc>
</thing>
<thing name="4">
<desc>b</desc>
</thing>
<thing name="3">
<desc>c</desc>
</thing>
<thing name="1">
<desc>d</desc>
</thing>
</things>
</foo>
XSLT:
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="text" />
<xsl:template match="/">
<xsl:for-each select="/foo/keys/key">
<xsl:sort select="/foo/things/thing[@name = current()/@id]"/>
<xsl:value-of select="@id"/>
</xsl:for-each>
</xsl:template>
</xsl:stylesheet>
Output:
2431
Upvotes: 1