Read XSLT 2.0 and XPath 2.0 Programmer's Reference, 4th Edition Online
Authors: Michael Kay
http://www.w3.org/2005/xpath-functions/collation/codepoint
XSLT 2.0 allows the pattern in the
match
attribute, and the expression in the
use
attribute, to reference global variables and to use the
key()
function to access other keys. But the definitions must not be circular; for example, if a key K makes use of the global variable V, then the value of V must not depend in any way on the key K.
There is no rule that stops two nodes having the same key value. For example, declaring a key for vehicle registration numbers in the example above does not mean that each registration number must be different. So a node can have more than one key value, and a key value can refer to more than one node.
To complicate things a bit further, there can be more than one
collation
attribute, if present.
A key can be used to select nodes in any document, not just the principal source document. This includes a temporary document constructed within the stylesheet.
The effect of calling
key(K, V, R)
, where
K
is a key name,
V
is a value, and
R
is a node, is to select every node
N
that satisfies all the following conditions:
If there are several nodes that satisfy these conditions, they are returned in document order, with duplicates eliminated.
If the third argument R is omitted, its effective value is
/
, which means that the function searches the whole of the document containing the context node.
Usage and Examples
Declaring a key has two effects: it simplifies the code you need to write to find the nodes with given values, and it is likely to make access faster.
The performance effect, of course, depends entirely on the implementation. It would be quite legitimate for an implementation to conduct a full search of the document each time the
key()
function was called. In practice, however, most implementations are likely to build an index or hash table, so there will be a one-time cost in building the index (for each document), but after this, access to nodes whose key value is known should be very fast.
The
Keys versus IDs
An alternative to using keys is to use XML-defined IDs. If you have attributes defined in a DTD or schema as being of type ID, you can find an element with a particular ID value using the
id()
function described in Chapter 13.
Why would you prefer to use keys, rather than relying on ID values? Keys have many advantages: