I am trying to select elements based on a number in their “title” element and then return them in a specific order. I’ve grouped them using a key, but when I access they key and apply-templates to the nodes, they’re not being returned in the order specified.
sample code:
<test>
<anElement>
<title>001 title</title>
</anElement>
<anElement>
<title>002 title</title>
</anElement>
<anElement>
<title>003 title</title>
</anElement>
<anElement>
<title>004 title</title>
</anElement>
<anElement>
<title>005 title</title>
</anElement>
<anElement>
<title>006 title</title>
</anElement>
<anElement>
<title>007 title</title>
</anElement>
<anElement>
<title>008 title</title>
</anElement>
<anElement>
<title>009 title</title>
</anElement>
<anElement>
<title>010 title</title>
</anElement>
</test>
when transformed with:
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
version="2.0">
<xsl:strip-space elements="*"/>
<xsl:output indent="yes"/>
<xsl:key name="keyNodes" match="//anElement" use="title/substring(., 1, 3)"/>
<xsl:template match="/">
<groupsOfNodes>
<aGroup>
<title>group one</title>
<members>
<xsl:apply-templates select="key('keyNodes', ('003', '002', '001'))"/>
</members>
</aGroup>
<aGroup>
<title>group one</title>
<members>
<xsl:apply-templates select="key('keyNodes', ('010', '009', '008'))"/>
</members>
</aGroup>
</groupsOfNodes>
</xsl:template>
<xsl:template match="anElement">
<para><xsl:apply-templates/></para>
</xsl:template>
</xsl:stylesheet>
gives this result:
<groupsOfNodes>
<aGroup>
<title>group one</title>
<members>
<para>001 title</para>
<para>002 title</para>
<para>003 title</para>
</members>
</aGroup>
<aGroup>
<title>group one</title>
<members>
<para>008 title</para>
<para>009 title</para>
<para>010 title</para>
</members>
</aGroup>
</groupsOfNodes>
Here’s an example of the desired result:
<members>
<para>003 title</para>
<para>002 title</para>
<para>001 title</para>
</members>
Is there any way to specify the order they’re processed, or do I have to use separate “apply-template” rules for each node in the key?
You could change your code to
As you are using XSLT 2.0 I also wonder why you use keys for grouping but that is a different issue.