Re: [xsl] Output sorted XHTML table for a subset of elements

Subject: Re: [xsl] Output sorted XHTML table for a subset of elements
From: Martin Honnen <Martin.Honnen@xxxxxx>
Date: Sun, 25 May 2008 12:53:57 +0200
Steven Davies wrote:

I know my sample data was a bit small but there are a lot more nodes in
my actual data set. Here's an attempt at a better example:

<users>
  <user name="alf"><lines>7</lines></user>
  <user name="bert"><lines>78</lines></user>
  <user name="charlie"><lines>731</lines></user>
  <user name="derek"><lines>62</lines></user>
  <user name="edward"><lines>93</lines></user>
  <user name="fred"><lines>823</lines></user>
  <user name="george"><lines>42</lines></user>
  <user name="harry"><lines>28</lines></user>
  <user name="ian"><lines>553</lines></user>
  <user name="joshua"><lines>92</lines></user>
  <user name="kevin"><lines>108</lines></user>
  <user name="luke"><lines>192</lines></user>
</users>

should give the output:

<table>
  <tr>
    <td>fred (823)</td>
    <td>charlie (731)</td>
    <td>ian (553)</td>
    <td>luke (192)</td>
    <td>kevin (108)</td>
  </tr>
  <tr>
    <td>edward (93)</td>
    <td>joshua (92)</td>
    <td>bert (78)</td>
    <td>derek (62)</td>
    <td>george (42)</td>
  </tr>
  <tr>
    <td>harry (28)</td>
  </tr>
</table>

Here is an XSLT 1.0 stylesheet making use of exslt:node-set:


<xsl:stylesheet
  xmlns:xsl="http://www.w3.org/1999/XSL/Transform";
  xmlns:exsl="http://exslt.org/common";
  exclude-result-prefixes="exsl"
  version="1.0">

<xsl:output method="html" indent="yes"/>

<xsl:param name="cols" select="5"/>

<xsl:param name="min-lines" select="25"/>

  <xsl:template match="/">
    <html>
      <head>
        <title>Example</title>
      </head>
      <body>
        <xsl:apply-templates select="users"/>
      </body>
    </html>
  </xsl:template>

<xsl:template match="users">
<xsl:variable name="sorted-users-rtf">
<data>
<xsl:for-each select="user[lines &gt; $min-lines]">
<xsl:sort select="lines" data-type="number" order="descending"/>
<xsl:copy-of select="."/>
</xsl:for-each>
</data>
</xsl:variable>
<xsl:variable name="sorted-users" select="exsl:node-set($sorted-users-rtf)/data/user"/>
<table>
<tbody>
<xsl:apply-templates select="$sorted-users[position() mod $cols = 1]" mode="row"/>
</tbody>
</table>
</xsl:template>


<xsl:template match="user" mode="row">
<tr>
<xsl:apply-templates select=". | following-sibling::user[position() &lt; $cols]" mode="cell"/>
</tr>
</xsl:template>


  <xsl:template match="user" mode="cell">
    <td>
      <xsl:value-of select="concat(@name, ' (', lines, ')')"/>
    </td>
  </xsl:template>

</xsl:stylesheet>

I think libXSLT supports exsl:node-set.


--


	Martin Honnen
	http://JavaScript.FAQTs.com/

Current Thread