Created
September 19, 2013 12:39
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?xml version="1.0" encoding="UTF-8"?> | |
<persons> | |
<person name="Tarzan" id="050676"/> | |
<person name="Donald" id="070754"/> | |
<person name="Dolly" id="231256"/> | |
</persons> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.