[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>
Here is a test of the idref() </xsl:text> <xsl:text>function:
</xsl:text> <xsl:for-each select="/parts-list/part"> <xsl:text>
 </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:
</xsl:text> <xsl:value-of select="idref(@part-id)/../../name" separator="
"/> <xsl:text>
</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().
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access