Grouping in XSLT

Tuesday 12 November 2002

Alex Moffat has an entry about how to group data with XSLT. This has got to be the biggest question people face as they climb the XSLT learning curve. It's a tough one to solve, because it's probably the most common operation that doesn't fall naturally out of the nested template model of XSLT, and whose simple and obvious looping solution is not available in XSLT.

Alex's solution is a clever use of tail recursion to loop and work around XSLT's lack of mutable variables. Luckily, when I was trying to figure out this same problem (for my blog archive page), I found Jeni Tennison's XSLT pages, including a page about grouping. She describes the Muenchian method, which is what I ended up using. Not only is it faster than Alex's method for very large data sets, but it has a natural place to drop in sorting so the original data set doesn't have to be pre-sorted. (Actually, Alex's method doesn't need the data to be sorted to get the grouping to work either, but the groups appear in whatever order they occurred in the data set. The Muenchian method lets me sort the groups and the records).

Another excellent resource for XSLT is Dave Pawson's XSL FAQ. The presentation is more of a firehose than Jeni's pages, so there's more information, but it's a little more work to find what you want.

tagged: » react


Add a comment:

Ignore this:
not displayed and no spam.
Leave this empty:
not searched.
Name and either email or www are required.
Don't put anything here:
Leave this empty:
URLs auto-link and some tags are allowed: <a><b><i><p><br><pre>.