Useful XSLT Tricks

This page is targeted at XSLT 1.0 users, and some (Muenchian grouping in particular) may have better options in XSLT 2 or later.

Using keys

The xsl:key instruction is used to look up all nodes matching a given pattern, that have a specific criteria. For example, with a bunch of 'shape' elements that have an attribute for color, you can get a list of all shapes that much each color.

Muenchian grouping

This technique allows you to group all nodes matching a specific criteria, by using a key. The core concept is that you match all members of every group, where it is the first node of it's group. This is done with:

<xsl:for-each select="node[generate-id() = generate-id(key('arbitrarykeyname',(criteria identifying the group))[1])]/>

Double Translate

The double translate technique is used to strip all characters EXCEPT a limited set from a string.

The translate function, aside from swapping all instances of one character with another, can remove all instances of a range of characters by specifying an empty string as the last parameter. You can use this method to derive a string containing everything BUT the characters you want to keep, and use that as a parameter to a second call to the function, which ultimately strips out only what you don't want. For example, to remove all non-numeric characters from a phone number:

translate('(123) 456-7890','0123456789','') = '() -'
translate('(123) 456-7890','() -','') = '1234567890'

Putting the original parameters in variables $input and $keep, we get:

translate($input,translate($input,$keep,''),'') = '1234567890'

Parameter passing

HTML metadata

Local data using namespaces

Importing documents

External functions

Two-pass solutions

Named templates and parameters