The Context

One of the most important concepts in XPath is the context. Everything we do in XPath is interpreted with respect to the context. You can think of an XML document as a hierarchy of directories in a filesystem. In our sonnet example, we could imagine that sonnet is a directory at the root level of the filesystem. The sonnet directory would, in turn, contain directories named auth:author, title, and lines. In this example, the context would be the current directory. If I go to a command line and execute a particular command (such as dir *.xsl), the results I get vary depending on the current directory. Similarly, the results of evaluating an XPath expression will probably vary based on the context.

[1.0] The XPath 1.0 context

Most of the time, we can think of the context as the node in the tree from which any expression is evaluated. To be completely accurate, the context consists of five things:

  • The context node (the “current directory”). The XPath expression is evaluated from this node.

  • Two integers, the context position and the context size. These integers are important when we’re processing a group of nodes. For example, we could write an XPath expression that selects all of the <li> elements in a given document. The context size refers to the number of <li> items selected by that expression, and the context position refers to the position of the <li> we’re currently processing.

  • A set of variables. This set includes names and values of all variables that are currently in ...

Get XSLT, 2nd Edition now with the O’Reilly learning platform.

O’Reilly members experience live online training, plus books, videos, and digital content from nearly 200 publishers.