Re: [xsl] Categorise Node by Unique Attribute

Subject: Re: [xsl] Categorise Node by Unique Attribute
From: Martin Honnen <Martin.Honnen@xxxxxx>
Date: Thu, 08 Jan 2009 13:15:14 +0100
William Warby wrote:

I want to group nodes in an XML file, placing a heading above each category. The category is defined in an attribute which may be the same for a series of records. The code sample below shows what I want to do. I've been going round in circles trying combinations of variables, templates, for-each loops and I just can't seem to get a handle on the problem. Any help would be very gratefully received.

Here is an XSLT 1.0 stylesheet that uses Muenchian grouping:


<xsl:stylesheet
  xmlns:xsl="http://www.w3.org/1999/XSL/Transform";
  version="1.0">

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

  <xsl:key name="cat"
           match="book"
           use="concat(parent::author/@name, '|', @genre)"/>

  <xsl:template match="/">
    <html lang="en">
      <head>
        <title>Books</title>
      </head>
      <body>
        <h1>Books</h1>
        <xsl:apply-templates select="authors/author"/>
      </body>
    </html>
  </xsl:template>

<xsl:template match="author">
<h2>
<xsl:value-of select="@name"/>
</h2>
<xsl:apply-templates select="book[generate-id() = generate-id(key('cat', concat(parent::author/@name, '|', @genre))[1])]" mode="group"/>
</xsl:template>


<xsl:template match="book" mode="group">
<h3>
<xsl:value-of select="@genre"/>
</h3>
<ul>
<xsl:apply-templates select="key('cat', concat(parent::author/@name, '|', @genre))"/>
</ul>
</xsl:template>


  <xsl:template match="book">
    <li>
      <xsl:value-of select="@name"/>
    </li>
  </xsl:template>

</xsl:stylesheet>

Read more about that on http://www.jenitennison.com/xslt/grouping/index.xml
--

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

Current Thread