A Smith A Smith - 8 days ago 5
ASP.NET (C#) Question

Allow XSLT table headings to be sorted in ascending and descending order on a ASP.NET web page

I have a ASP.NET web page which has several XSLT's to transform data in a xml file. The XSLT manipulates the data and presents it in a table.

Is it possible to allow the user to click on each of the table headings to sort the values in ascending or descending order?

The back end code is in VB.net in case it helps?

Answer

Yes, just pass to the transformation the sort order and data-type as parameters:

Here is a short example:

<xsl:stylesheet version="1.0"
 xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
 <xsl:output omit-xml-declaration="yes" indent="yes"/>
 <xsl:strip-space elements="*"/>

 <xsl:param name="pSortField" select="'age'"/>
 <xsl:param name="pSortOrder" select="'descending'"/>
 <xsl:param name="pSortDataType" select="'number'"/>

 <xsl:template match="/*">
     <xsl:copy>
       <xsl:for-each select="*">
         <xsl:sort select="*[name()=$pSortField]"
                   order="{$pSortOrder}" data-type="{$pSortDataType}"/>
         <xsl:copy-of select="."/>
       </xsl:for-each>
     </xsl:copy>
 </xsl:template>
</xsl:stylesheet>

When this transformation is applied on the following XML document:

<people>
  <person>
    <age>15</age>
    <name>Anna</name>
  </person>
  <person>
    <age>22</age>
    <name>Kim</name>
  </person>
  <person>
    <age>31</age>
    <name>Harry</name>
  </person>
  <person>
    <age>27</age>
    <name>Peter</name>
  </person>
</people>

the wanted, correct result is produced (all person elements sorted by age as number in descending order):

<people>
   <person>
      <age>31</age>
      <name>Harry</name>
   </person>
   <person>
      <age>27</age>
      <name>Peter</name>
   </person>
   <person>
      <age>22</age>
      <name>Kim</name>
   </person>
   <person>
      <age>15</age>
      <name>Anna</name>
   </person>
</people>

Just change the value of the parameters and other sort results will be produced.

With these parameters:

 <xsl:param name="pSortField" select="'name'"/>
 <xsl:param name="pSortOrder" select="'ascending'"/>
 <xsl:param name="pSortDataType" select="'text'"/>

the result is now:

<people>
   <person>
      <age>15</age>
      <name>Anna</name>
   </person>
   <person>
      <age>31</age>
      <name>Harry</name>
   </person>
   <person>
      <age>22</age>
      <name>Kim</name>
   </person>
   <person>
      <age>27</age>
      <name>Peter</name>
   </person>
</people>