Generating Links with the key() Function

In the modified parts list document we looked at a moment ago, we added a <supplier> to each <part>. We also added a country attribute to the <supplier> element. If you look at the document structure as defined in the embedded DTD (or the external schema), you’ll notice that the vendor-id and country attributes of the <supplier> element don’t have a datatype of ID, and that the supplier attribute of the <part> element is not an IDREF.

We want to retrieve all the parts that are provided by a particular country. If we defined the country attribute to be of type ID, we could only have one supplier from each country. Clearly that’s an unacceptable limitation on our document.

Now that we’ve created a more flexible XML document, we’ll use the key() function to process our document. We’ll use two keys here. The first retrieves all of the <supplier> elements that match a given country name. The second retrieves all of the <part> elements whose supplier attribute matches a given supplier’s ID. Here’s the stylesheet:

<?xml version="1.0"?>
<!-- key.xsl -->
<xsl:stylesheet version="1.0"
  xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

  <xsl:output method="html"/>

  <xsl:param name="country-name"/>

  <xsl:key name="supplier-by-country" match="supplier" use="@country"/>
  <xsl:key name="part-by-supplier" match="part" use="@supplier"/> <xsl:template match="/"> <html> <head> <title> <xsl:text>Parts from </xsl:text> <xsl:value-of select="$country-name"/> </title> ...

Get XSLT, 2nd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.