03 May 2006

xslt: using keys

One feature of XSLT that I haven't used much is keys. This posting on Simon Woodside's blog describes how to use xsl:key as an index for large XML files:
xsl:key pre-creates an index on the table, based on whatever attributes or nodes you choose. For example, if your xml looks like:

<foo>
<bar name="X">...</bar>
<bar name="Y">...</bar>
...
</foo>

and you need to select '/foo/bar[@name='X']', doing so directly is cheap if your XML is small. But if it's big you should create a key, especially if you're doing selections of that type frequently. So before your templates you need:

<xsl:key name="bar_by_name" match="/foo/bar" use="@name"/>

Then when you need a piece of data you use 'key('bar_by_name','X')'.

You can even make up a concatenated index, if you need a multi-part search. i.e.:
<xsl:key name="foo" match="/foo/bar" use="concat(@name,'-',@type)"/>
and then select 'key('foo',concat($foo_name,'-',$foo_type))'. Just make sure that the string you're using to separate the search elements isn't valid as part of the content of the elements.

Proper application of xsl:key can be very useful. One of our translations is taking flat database dumps with approximately 10,000 nodes and converting them to a structured format, based on the structure of our database, with approximately 145,000 nodes. Using xsltproc (which is slower than Saxon, but more widely available) that translation takes 30-40 seconds. Without keys it was taking over 10 minutes.
Incidentally, Simon's blogging engine (opensource) was created by him using the opensource AXKit XML content management framework and is powered largely by XSLT transforming XML content files.

Comments: Post a Comment

Subscribe to Post Comments [Atom]





<< Home

This page is powered by Blogger. Isn't yours?

Subscribe to Posts [Atom]