XML technologies / XSLT / Introduction to XSLT 2.0 / XSLT and XPath – round three / Keys and identifiers / Reading genuine identifiers with function id()

(Excerpt from “XSLT 2.0 & XPath 2.0” by Frank Bongers, chapter 3.)

The id() function selects elements by their unique identifiers, declared in a DTD or schema with type ID. It therefore returns a sequence of element nodes, since other node types cannot have identifiers. Searches always use the document containing the call’s context node.

The argument, an XPath expression, is interpreted as a list of NMTOKENS; each NMTOKEN represents a sought identifier. Evaluating the XPath expression ultimately gives a string containing concatenated, not sequenced, candidate identifiers (candidate ID values), separated by spaces.

The result is a sequence of elements whose ID-typed identifiers have one of the sought values. If no element matches, the sequence is empty; no error occurs.

The token list is obtained in two ways.

The argument evaluates to a sequence.
Here, the list comes from all nodes’ string values in the sequence. Every distinct word in those element text contents is checked as a possible identifier.

Suppose the sequence’s string value is “Das ist ein Beispiel”. The identifier values sought are then "Das", "ist", "ein" and "Beispiel". The result contains elements with those identifiers, if any. This search is rather like a shotgun blast.

The argument yields an atomic value.
If the argument is not a node sequence, it is converted directly to a string treated as a token list. The result again comprises all elements whose IDs match a token.

Some examples clarify this:

id("beispiel")

selects the element with ID value "beispiel", wherever it is relative to the current node. The result is a node sequence, here containing at most one element, so a path expression can be applied directly:

id("beispiel")/child::abschnitt[position()=4]

selects the fourth child element <abschnitt> of the element whose ID has value "beispiel".

The id() function ensures at most one element node is returned. Instead of function id(), a similar but not identical path expression is possible:

//*[@*="beispiel"]/child::abschnitt[position()=4]

First, this selects all elements with an attribute of any name whose value is beispiel. Second, it selects each element’s fourth child named abschnitt.

Crucially, this does not test for type ID, although an ID with that value would also match. It also includes children of elements whose matching attributes are not IDs.

   

back to top