O'Reilly logo

XSLT, 2nd Edition by Doug Tidwell

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

A Stylesheet That Uses the id() Function

Let’s look at our desired output. What we want is a simple text document that lists all of the part names for each component, which should look like this:

Here is a test of the id() function:

  Turnip Twaddler (component #C28392-33-TT) uses these parts:
    Spanner
    Feather Duster
    Grommet
    Paring Knife

  Prawn Goader (component #C28813-70-PG) uses these parts:
    Paring Knife
    Mucilage
    Ribbon Curler

...

  Olive Bruiser (component #C28772-63-OB) uses these parts:
    Pitter
    Patter

The stylesheet to generate these results is pretty straightforward:

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

  <xsl:output method="text"/>

  <xsl:template match="/">
    <xsl:text>&#xA;Here is a test of the id() </xsl:text>
    <xsl:text>function:&#xA;</xsl:text>

    <xsl:for-each select="/parts-list/component">
      <xsl:text>&#xA;  </xsl:text>
      <xsl:value-of select="name"/>
      <xsl:text> (component #</xsl:text>
      <xsl:value-of select="@component-id"/>
      <xsl:text>) uses these parts:&#xA;    </xsl:text>
      <xsl:for-each select="id(partref/@refid)">
        <xsl:value-of select="name"/>
        <xsl:text>&#xA;    </xsl:text>
      </xsl:for-each>
    </xsl:for-each>
  </xsl:template>
</xsl:stylesheet>

We call the id() function, which returns a node-set/sequence of all the nodes that match all of the refid attributes of the <partref> elements in each component. Each item in the node-set is the actual <part> element, so the XPath expression select="name" returns the name of the ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required