XSL Grouping using the muenchian method

Posted: 15 March 2010 in Components, Pages, SitePublisher, Sites, XSL

We all know that grouping elements in XSL 1.0 is a nightmare. However, we can do it using the muenchian method.

Given the following XML as an example, we’ll give you an understanding of how it works:

<books>
<book>
<title>The Lord of the Rings: The Fellowship of the Ring </title>
<author>J.R.R. Tolkien</author>
</book>
<book>
<title>The Lord of the Rings: The Two Towers</title>
<author>J.R.R. Tolkien</author>
</book>
<book>
<title>The Lord of the Rings: The Return of the King</title>
<author>J.R.R. Tolkien</author>
</book>
<book>
<title>Emma</title>
<author>Jane Austen</author>
</book>
<book>
<title>Pride and Prejudice</title>
<author>Jane Austen</author>
</book>
<book>
<title>Sense and Sensibility</title>
<author>Jane Austen</author>
</book>
</books>

First, we define the key we want to group on. The match attribute define which elements will have the key added to them.
The use attribute, defines the value of the key.

<xsl:key name="authorKey" match="book" use="author" />

Now, each book element has a key named authorKey with the the author of the book as a value.

We will, create two templates to deal with the group as a whole (for the group heading and counts for example) and each item in the group (the detail part).

the key function returns the set of elements matching the value given. What we do is find out the first of element of each key we have then call the template on that one element, with a mode of group:

<xsl:template match="/books">
<xsl:apply-templates select="book[generate-id(.) = generate-id(key('authorKey',author)[1])]" />
</xsl:template>
<xsl:template match="book" mode="group">
<h1><xsl:value-of select="author" /></h1>
This author has written <xsl:value-of select="count(key('authorKey',author))" /> books.
<ul>
<xsl:apply-templates select="key(authorKey,author)" mode="entry"/>
</ul>
</xsl:template>
<xsl:template match="book" mode="entry">
<li>
<xsl:value-of select="title" />
</li>
</xsl:template>

Two explanations are better than one, so you can have a look at this post too.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s