Read XSLT 2.0 and XPath 2.0 Programmer's Reference, 4th Edition Online
Authors: Michael Kay
Whitespace is allowed between the
$
sign and the
QName
, though it is rarely used (it was not permitted in XPath 1.0).
Usage
The
QName
must match the name of a variable that is in scope at the point where the expression containing the variable name appears. A variable can be declared either within a containing
for
,
some
, or
every
expression, or (in XSLT) in an
The value of the variable reference is whatever value has been assigned to it by the matching
for
,
some
, or
every
expression, or (with XSLT) the matching
A variable reference can be used anywhere in an XPath expression where a value is required. It cannot be used to represent concepts of the language other than values; for example, you can't use a variable in place of a name, a node type, or an axis. Nor can you use a variable to hold an entire expression.
A common misunderstanding about variables is to write a path expression such as:
/booklist/book/$property
thinking that if the value of
$property
is the string “title”, then this is equivalent to writing:
/booklist/book/title
You can do this sort of thing in a shell scripting language, where variables work by textual substitution: in that kind of language the content of a variable can hold any part of an expression. But in XPath, variables hold values, not pieces of an expression. The actual meaning of the above expression is:
/booklist/book/“title”
which will return the string “title” once for each book element.
The way to achieve the desired effect is to write:
/booklist/book/*[local-name() eq $property]
Some processors (including Saxon) offer an
evaluate()
extension function, which allows you to construct an XPath expression at runtime, from a string which might be held in a variable. But this capability is not present in the standard.