It is often necessary to group elements based on certain attributes or subelements. Consider our XML document that contains the largest cities in America. We might want to output these cities by state as shown below.
In XSLT 1.0, there is no tag meant for grouping, but there are at least a couple of ways to get the job done. The most efficient way
to do this is to use a method called the Muencian method after Steve Muench who created it. This method requires a good understanding of the
generate-id() function discussed below.
The generate-id() Function
The generate-id() function creates ids that uniquely identify a node in an XML document. It takes a single argument: the node-set to identify. The value of the generated id is based on the first node in the node-set, and the same id will be generated no matter how the node is retrieved. To illustrate this, take a look at the following two files.
As shown below, we can use this knowledge to find the first City element with a specific State attribute.
Okay. Now let's get back to grouping. We've learned how to use generate-id() and keys pick just one city from every state. Another way to look at this is that we've learned how to retrieve each distinct state once and only once. To group by state, we need loop through the City elements for each state and return all the cities in that state. But we don't need to go through the whole node tree again, because we have a key that contains all City elements by State. Take a look at the following code.
We also sort the outer loop by state according to the number of cities per state. This is done by counting the number of City elements matched by the key() function: