Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Limiting the number of sorted results from for-each loop XSL

Tags:

xml

xslt

I'm trying to see if it's possible to have a for-each loop setup in an XSL file that goes through a number of nodes, but I want to make it so that only the top 3 results are returned e.g.

<course>
<unit>
    <result>80</result>
</unit>
<unit>
        <result>77</result>
</unit>
<unit>
        <result>96</result>
</unit>
<unit>
    <result>69</result>
</unit>
</course>

and then use a for-each loop similar to the following:

<xsl:for-each select="/course/unit">
<xsl:sort select="result" data-type="number" order="descending"/>
<xsl:value-of select="result"/>
</xsl:for-each>

But the problem is if I do something like: <xsl:for-each select="/course/unit[position() &lt;= 3]"> It will grab the first 3 nodes and then sort it which isn't what I need, I want it to get the 3 highest marks and return those nodes to display the info rather than sort the results after they have gone through all the loop. I'm sure there is a simple way of achieving this without using templates, so any hints will be greatly appreciated.

like image 998
benh11858 Avatar asked Sep 17 '13 14:09

benh11858


1 Answers

Use

<xsl:for-each select="/course/unit">
<xsl:sort select="result" data-type="number" order="descending"/>
  <xsl:if test="position() &lt;= 3">
    <xsl:value-of select="result"/>
  </xsl:if>
</xsl:for-each>
like image 178
Martin Honnen Avatar answered Oct 12 '22 07:10

Martin Honnen