Microsoft XML Core Services (MSXML) 5.0 for Microsoft Office - XSLT Developer's Guide

Using XSLT Keys to Group Data

One of the most common uses of keys is for grouping data in a document. We've already discussed the <xsl:sort> element in Sorting with XSLT. However, with sorting alone, you must repeat each of the items establishing a category. What if you want to display the category only once, followed by a list of all items that fall under it?

The public library participating in Scootney's promotional exhibit wants to produce a single Web page that groups the titles in the exhibit in two ways. One grouping will show the titles grouped by category. The other grouping will show them grouped by author.

The style sheet developed by the library, lib_cat2.xsl, defines the following two keys that correspond to these two groupings.

There are also two template rules for the root <catalog> element. These template rules use modes to enable the element to be processed twice—once for each grouping. These template rules are invoked by <xsl:apply-templates> elements within the template rule for the document root:

<xsl:template match="/">
...
         <xsl:apply-templates select="catalog" mode="grp_categ"/>
         <xsl:apply-templates select="catalog" mode="grp_author"/>
...
</xsl:template>

The two template rules for the <catalog> element take two slightly different approaches to the problem of grouping, although both use keys to do so. The following topics describe these two approaches.

Files Used for This Topic