Differences between XPath Expressions and XSLT Patterns

MSXML 5.0 SDK

Microsoft XML Core Services (MSXML) 5.0 for Microsoft Office - XPath Developer's Guide

Differences between XPath Expressions and XSLT Patterns

An Extensible Stylesheet Language Transformations (XSLT) pattern may appear in a number of places in a style sheet:

  • As the value of the match attribute of an <xsl:template> element. (This is the most common use of XSLT patterns.)
  • As the value of the match attribute of an <xsl:key> element.
  • As the values of the count and from attributes of an <xsl:number> element.

The purpose of a pattern is to restrict the set of candidate nodes in a node-set to just those nodes that meet a particular condition, or set of conditions. For instance:

<xsl:template match="//attribute::invoice_num[.='X00456']">

restricts the candidate nodes for the template rule just to the element(s) with an invoice_num attribute whose value is "X00456". This works even though from any given context node, in theory all other nodes in the documents are reachable candidates.

All XSLT patterns are also XML Path Language (XPath) expressions. However, the reverse is not always true: not all XPath expressions are XSLT patterns. For instance:

round(sales)

is a legitimate XPath expression, which returns the value of the <sales> element rounded to the nearest integer. But:

<xsl:template match="round(sales)">

is not a legitimate way to open an XSLT <xsl:template> element. Even though it refers to a node-set (sales) relative to the context node, taken as a whole the expression does nothing to constrain the universe of all possible candidate nodes at that point to a subset of them. Thus, such XPath expressions must always appear in a pattern in some other form, such as within a predicate.

For example, we could use the round(sales) expression in this way in an XSLT pattern:

<xsl:template match=".//*[round(sales) &lt; 5000]">

This says to restrict the universe of possible candidate nodes to those which are descended from the context node (.//), with any name (*), whose <sales> children have a value less than 5000 ([round(sales) &lt; 5000]).