In XSLT, how can you sort using an indirect key?

Posted by edholder on Stack Overflow See other posts from Stack Overflow or by edholder
Published on 2010-05-20T13:41:43Z Indexed on 2010/05/20 13:50 UTC
Read the original article Hit count: 196

Filed under:
|
|

I am having trouble getting xsl:sort to understand the scope of the attributes I am referencing. Here is an XML sample document to illustrate:

<Root>
  <DrinkSelections>
    <Drink id=1000 name="Coffee"/>
    <Drink id=1001 name="Water"/>
    <Drink id=1002 name="Tea"/>
    <Drink id=1003 name="Almost But Not Quite Entirely Unlike Tea"/>
  </DrinkSelections>

  <CustomerOrder>
    <Drinks>
      <Drink oid="1001"/>
      <Drink oid="1002"/>
      <Drink oid="1003"/>
    </Drinks>
  </CustomerOrder

</Root>

I want to produce a list of drinks (sorted by name) contained in the CustomerOrder. Here is the XSLT code I am fiddling with:

<xsl:for-each select="/Root/CustomerOrder/Drinks/Drink">
   <xsl:sort select="/Root/DrinkSelections/Drink[@id = @oid]/@name"/>
   <xsl:variable name=var_oid select="@oid"/>
   <xsl:value-of select="/Root/DrinkSelections/Drink[@id = $var_oid]/@name"/>
</xsl:for-each>

Apparently, the xsl:sort command is trying to apply the "oid" attribute to the Drink elements in DrinkSelections, rather than local Drink element.

I can get around this using a variable, as in the xsl:value-of statement. But since xsl:sort must be the first statement after the xsl:for-each statement, I can't insert the xsl:variable statement before xsl:sort.

Is there a way to explicitly state that the attribute value should be taken from the "local" element?

© Stack Overflow or respective owner

Related posts about xslt

Related posts about attributes