Skip to content

Instantly share code, notes, and snippets.

@ssp
Created September 19, 2013 12:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ssp/6622824 to your computer and use it in GitHub Desktop.
Save ssp/6622824 to your computer and use it in GitHub Desktop.
An attempt to understand xsl:key and the key() function and why it is not possible to insert the keys into the document itself.
<?xml version="1.0" encoding="UTF-8"?>
<!--
Attempt to use xsl:key on data not stored in the document itself.
We _can_ load external XML into a variable using document() and use
the key() function on that.
We _cannot_ include the XML into our stylesheet and use the key()
function on that.
The reason seems to be that using select="" will give us a variable
containing a set of nodes while other ways return result tree fragments
which cannot be used with further select statements.
A workaround is to use the node-set() function for converting the result
tree fragment to a node set. It is not part of XSL 1.
http://stackoverflow.com/a/5303159
The example uses for-each on the document to make it the context node
as hinted in:
http://www.oxygenxml.com/archives/xsl-list/200105/msg00546.html
-->
<xsl:stylesheet
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
version="1.0"
>
<xsl:key name="preg" match="person" use="@id"/>
<xsl:template match="/">
<output>
<xsl:for-each select="document('persons.xml')">
<xsl:value-of select="key('preg', '050676')/@name"/>
</xsl:for-each>
</output>
</xsl:template>
</xsl:stylesheet>
<?xml version="1.0" encoding="UTF-8"?>
<persons>
<person name="Tarzan" id="050676"/>
<person name="Donald" id="070754"/>
<person name="Dolly" id="231256"/>
</persons>
@roymath-zz
Copy link

Thanks! found this extremely helpful - was struggling to get a good example that worked w/xslt1.0...The "key" understanding that your code helped me with was that 'key' is a "query function", not a set of values.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment