Search code examples
xmlxsltxslt-1.0xslt-2.0xslt-grouping

XSLT group-by throws an error


The xml is as below:

<Words num="1">
    <Word>
        <search>Apple</search>
        <replace>Fruit</replace>
    </Word>
    <Word num="2">
        <search>Honda</search>
        <replace>Car</replace>
    </Word>
    <Word num="3">
        <search>Banana</search>
        <replace>Fruit</replace>
    </Word>
</Words>

I want to convert it in a table in html output (not xml output) - using grouping functionality (group by replace).

<table>
   <tr><td>Replace: Fruit</td></tr>
   <tr><td>Replace: Car</td></tr>
</table>

The code I've written is:

<?xml version="1.0" encoding="UTF-8"?>    
<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
   <xsl:output method="html" />

   <xsl:template match="/">
      <html>             
         <body>                
            <table border="1">
               <xsl:for-each-group select="Words/Word" group-by="replace">
                  <tr>
                     <td>Replace: <xsl:value-of select="current-grouping-key()"/></td>
                  </tr>               
               </xsl:for-each-group>
            </table>
         </body>
      </html>       
   </xsl:template>
</xsl:stylesheet>     

When opened xml file(linked with xslt) in Firefox, it returns "Error during XSLT transformation: XSLT transformation failed."

Can anyone provide me with guidance?

Thanks.


Solution

  • The XSLT supported in browsers like Mozilla, IE, Opera, Chrome is limited to XSLT version 1.0 which does not support for-each-group. With XSLT 1.0 you are limited to Muenchian grouping http://www.jenitennison.com/xslt/grouping/muenchian.xml.

    As an alternative you could consider using Saxon CE, which provides XSLT 2.0 in the browser. See http://www.saxonica.com/ce/index.xml.