Read XSLT 2.0 and XPath 2.0 Programmer's Reference, 4th Edition Online
Authors: Michael Kay
This is true because nothing can change between the variables being defined and being used. The source document can't change, and the values of the variables
$this
and
$matches
can't change. The context (for example the current position in the source document) can change, but in this example (a) it doesn't, and (b) the expressions don't depend on the context anyway.
I call these
convenience variables
because you could get by without them if you had to (though there might be a performance hit). They can be used either as global variables or as local variables. Creating global convenience variables that refer to sets of nodes in the source document is often a useful programming technique; for example:
These act rather like views in an SQL database.
Variables to Capture Context-Sensitive Values
These variables are most often useful in conjunction with
Example: Using a Variable for Context-Sensitive Values
This example shows how a variable can be used to hold on to information that depends on the context, for use when the context has changed.
Source
The source file is
opera.xml
. It contains a list of operas and details of their composers.
Stylesheet
The stylesheet is the file
opera.xsl
. This is a complete stylesheet: It uses the simplified stylesheet syntax described on page 125, in Chapter 3.
The stylesheet contains two nested
c
to the context node (the current composer). In the expression controlling the inner loop, this variable is used. It would not be correct to use
.
in place of
$c
, because the
current()
function here (this function is described on page 734, in Chapter 13), but there are other cases where a variable is necessary.
xmlns:xsl=“http://www.w3.org/1999/XSL/Transform”
xsl:version=“2.0”>
Programme
select=“concat(fullname, ‘ (‘, born, ‘-’, died, ‘)’)”/>
Output
See
Figure 6-18
.
One case where context variables are very useful is when handling multiple source documents.
In any stylesheet that handles multiple source documents, it is useful to include a global variable that refers to the document node of the principal source document, thus:
This means it is always possible to refer to the source document by using this variable. Without this, when the context node is in a secondary document, there is no way of accessing data from the principal document.
For example, the expression
//item
refers to all
$root//item
.