Re: [xsl] Writing a stylesheet to create another XML Document

Subject: Re: [xsl] Writing a stylesheet to create another XML Document
From: Jeni Tennison <jeni@xxxxxxxxxxxxxxxx>
Date: Tue, 2 Apr 2002 19:19:43 +0100
Hi Kunal,

>> You're using the document() function just right, to get hold of the
>> content of the Author.xml document. If you're searching for particular
>> Authors by id a lot, you should store the Author elements in a global
>> variable:
>>
>> <xsl:variable name="authors"
>>               select="document('Author.xml')/AuthorList/Author" />
>>
>> Or you should use a key to get hold of the Author elements quickly,
>> especially if there are a lot of them. There are examples about how to
>> do that in the XSLT Rec, but ask if you want to see how.
>
> I'd greatly appreciate if you could comment on using the key
> function in this scenario.

Sure. You need to find Author elements by their id attribute, so you
need to declare a key that does just that:

<xsl:key name="authors" match="Author" use="@id" />

This enables you to do:

  key('authors', '03')

to get the Author element whose id attribute has a value of '03'
within the current document.

The difficulty with using this key is that the Author elements that
you're interested in are actually in a different document from the
node that you're processing at the point you want to find the Author
element. Keys only look in the document holding the current node, so
you need to swap context to the Author.xml document in order to search
that document for the Author element that you're after, which you can
do most easily with an xsl:for-each.

You should first declare a global variable that holds the root node
(or document element, or indeed any other single node) in the
Author.xml document:

<xsl:variable name="authors" select="document('Author.xml')" />

Then in the template that matches Author elements (in the original
source document), you should use an xsl:for-each to switch to
Authors.xml in order to search it for the relevant authors using the
key:

<xsl:template match="Author">
  <xsl:variable name="id" select="@id" />
  <xsl:for-each select="$authors">
    <xsl:copy-of select="key('authors', $id)" />
  </xsl:for-each>
</xsl:template>

Cheers,

Jeni

---
Jeni Tennison
http://www.jenitennison.com/


 XSL-List info and archive:  http://www.mulberrytech.com/xsl/xsl-list


Current Thread