XML technologies / XSLT / Introduction to XSLT 2.0 / XSLT and XPath – round three / Keys and identifiers / Comparing keys and IDs
(Excerpt from “XSLT 2.0 & XPath 2.0” by Frank Bongers, chapter 3.)
Whereas targets of id() must be identifiers declared in the DTD, with corresponding limitations, key() has no such restrictions. Think of a key as a generalized ID generated only when the stylesheet runs. Compare the concepts:
ID – declared in the DTD
An attribute of typeIDmust be declared in the DTD. If the XSLT processor does not process an external DTD, which it is not required to do, an attribute cannot be recognized as anIDattribute. The same can happen if the document declaresstandalone="yes", although there should then be no external DTD. Reading IDs withid()is therefore not always straightforward.
Keys – declared in the stylesheet
A key is defined in the stylesheet withxsl:keyand read withkey(), independently of the DTD and its validation role.
ID – one set, one ID per element
An XML document has only one identifier set, not several independent ones. Each element can have at most one identifier, and no other element can reuse its value for its own identifier. The name of the attribute of typeIDdoes not matter.
Keys – multiple parallel sets
Many identical key values can identify different nodes. Since keys have both names and values, values may repeat under another name and identify other elements. Values of attributes of typeIDcannot repeat, even with different attribute names; what matters is typeID.
ID – the identifier is always in an attribute
To identify an element by an ID, its identifying value must be in an attribute of typeID, not in its string content or a child element.
Keys – freely composed identifiers
A named key’s value can be in any suitable place: an attribute, the element itself, a child, or even spread across several places. An XPath expression specifies where to find it.
ID – the identifier value must be a QName.
An identifier value must be a qualified name and therefore cannot contain spaces.
Keys – any value
A key value can be any string, without QName restrictions. It may contain spaces and thus multiple words.
Especially useful, keys can be built from several sources at once, such as two or more attributes or child contents of an element. Just write the appropriate XPath expression. This makes xsl:key and key() powerful tools.
Copyright © Galileo Press, Bonn 2008
You may print the online version for your private use.
Otherwise, this chapter from “XSLT 2.0 & XPath 2.0 ― Das umfassende Handbuch” is subject to the same conditions as the bound edition. The work, including all its parts, is protected by copyright. All rights reserved, including reproduction, translation, microfilming, and storage and processing in electronic systems.
Galileo Press, Rheinwerkallee 4, 53227 Bonn