1

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...

1 Answer 1

1

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
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks. It doesn't solve my problem but this isn't your fault. In my real style sheet the "keys" and the "things" reside in different documents (the keys being included via document()) and somehow I can't access both of them at the same time. I think I'll accept your answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.