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
sonnet is a directory at the
root level of the filesystem. The
sonnet directory would, in turn, contain
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
*.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.
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
A set of variables. This set includes names and values of all variables that are currently in ...