Re: [xsl] xsl:key and document()

Subject: Re: [xsl] xsl:key and document()
From: Jeni Tennison <mail@xxxxxxxxxxxxxxxx>
Date: Sat, 6 Jan 2001 11:28:49 +0000
Hi Robert,

> I'm trying to build a XSL doc that uses a couple of keys (using
> MSXML 3.0). The values I want for these keys, however, are located
> in XML documents other than the main document. However, I haven't
> been able to use xsl:key to reference external documents.

Yes, annoying isn't it? ;) The thing you have to realise is that the
key definition uses a *match pattern*, not a *select expression*, to
identify the nodes that it indexes. When key() is called, it looks for
nodes that match the match pattern for the key *in the document
holding the current node*, and indexes them.

So, to create a key that will match nodes in your separate document,
you need an xsl:key element that matches those nodes and don't need to
worry about pointing out they're in a different document at all:

<xsl:key name="LUType" match="record" use="@ID" />

It's when you *use* the key that you determine which document is
searched.  You need to change the current node to be in the document
you want to search in; usually you'd do this with an xsl:for-each:

  <xsl:for-each select="document('LUType.xml')">
     <xsl:value-of select="key('LUType', $keyValue)" />

Remember that within the xsl:for-each, the current node is the
document root node, and therefore if you use an expression in the key
value then it will be resolved relative to that document's root node:
usually you'll want to use a variable.  Remember also that it's an
xsl:for-each, but actually you're just using it to change the current
node - don't have a select expression that contains more than one node
or it will repeat output left, right and centre.

There are occasions where this limitation on key() causes real
problems, particularly when you're using key() within a sort select
expression, but usually the above method fits in with what you're
trying to achieve.  Let us know if not.

I hope that helps,


Jeni Tennison

 XSL-List info and archive:

Current Thread