Re: xsl:key

Subject: Re: xsl:key
From: Jeni Tennison <Jeni.Tennison@xxxxxxxxxxxxxxxx>
Date: Wed, 21 Jun 2000 10:53:28 +0100

>I would like to extract all paragraphs that have an attribute
>of doc equal to contract. Instead I only receive the following
>output and I was hoping to understand why?

OK.  First let's have a look at your input:

  <Target doc="contract"/>
     <Para>CONTRACT para destined for output to contract.xml</Para>
.... other para's all with different doc value according to DTD

Note here that the 'Target' element is an empty one: it does not contain
the paragraph that it refers to.  This contradicts your DTD, which says
that the 'Target' element should *contain* a 'Content' element rather than
be *followed by* a 'Para' element.  I'll assume that your sample XML is
what you want, rather than the DTD.

Now have a look at your key:

<xsl:key name="blueprint" match="Target" use="@doc"/>

Here you are making a key in which the 'Target' elements are indexed
according to their 'doc' attribute.  When you use it later:

<xsl:template match="Destination">
  <xsl:element name="{name()}">
    <xsl:copy-of select="key('blueprint', '$contractType')"/>

you want to get the *Para* elements that follow that particular 'Target'
element, but instead are getting the 'Target' elements themselves (or would
be if you didn't quote the $contractType variable).

So, I'd change the way you define and use the key.  Keys should generally
match the elements that you're actually interested in, which in this case
is the 'Para' elements.  You can use anything reachable by an XPath
expression from that element as a key, so:

<xsl:key name="blueprint" match="Para"  use="../Target/@doc" />


<xsl:template match="Destination">
  <xsl:element name="{name()}">
    <xsl:copy-of select="key('blueprint', $contractType)"/>

Note that this will only get one paragraph - if there are multiple
paragraphs with the same value for the 'doc' attribute, then you should
iterate over them using xsl:for-each.

This has been tested on your sample input and works with SAXON.

I hope that this helps,


Dr Jeni Tennison
Epistemics Ltd, Strelley Hall, Nottingham, NG8 6PE
Telephone 0115 9061301 ? Fax 0115 9061304 ? Email

 XSL-List info and archive:

Current Thread