Relative and Absolute Expressions

The XPath specification talks about two kinds of XPath expressions, relative and absolute. Our previous example is a relative XPath expression because the nodes it specifies depend on the current context. An absolute XPath expression begins with a slash (/), which tells the XSLT processor to start at the root of the document, regardless of the current context. In other words, you can evaluate an absolute XPath expression from any context node you want, and the results will be the same. Here’s an absolute XPath expression:

<xsl:apply-templates select="/sonnet/lines/line"/>

The good thing about an absolute expression is that you don’t have to worry about the context node. Another benefit is that it makes it easy for the XSLT processor to find all nodes that match this expression: what we’ve said in this expression is that there must be a <sonnet> element at the root of the document, that element must contain at least one <lines> element, and that at least one of those <lines> elements must contain at least one <line> element. If any of those conditions fail, the XSLT processor can stop looking through the tree and return an empty node-set.

A disadvantage of using absolute XPath expressions is that it makes your templates more difficult to reuse. Both of these templates process <line> elements, but the second one is more difficult to reuse:

<xsl:template match="line">
  ...
</xsl:template>

<xsl:template match="/sonnet/lines/line">
  ...
</xsl:template>

If the ...

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.