[2.0] The idref() Function

In the previous stylesheet, it was tedious to use the id() function in reverse, going from something with a given ID to the elements that reference it. Because this is a fairly common task, XSLT 2.0 adds the idref() function. Given an ID, idref() returns all of the elements that reference it. Here’s a simple stylesheet that works with our parts list:

<?xml version="1.0"?>
<!-- idref.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 idref() </xsl:text>
    <xsl:text>function:&#xA;</xsl:text>

    <xsl:for-each select="/parts-list/part">
      <xsl:text>&#xA;  </xsl:text>
      <xsl:value-of select="name"/>
      <xsl:text> (part #</xsl:text>
      <xsl:value-of select="@part-id"/>
      <xsl:text>) is used in these products:&#xA;</xsl:text>
      <xsl:value-of select="idref(@part-id)/../../name"
        separator="&#xA;"/> 
      <xsl:text>&#xA;</xsl:text>
    </xsl:for-each>
  </xsl:template>
</xsl:stylesheet>

In this stylesheet, we can do everything with a single <xsl:value-of> element. Notice that the idref() function returns the matching attributes; that’s why we use the XPath expression idref(@part-id)/../../name to get the name of the component. The parent of the attribute is a <partref> element and its parent is a <component>. The component’s <name> child is what we want here.

Finally, the new idref() function works with the IDREFS datatype, just like id().

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.