Using Key and Keyref for XML Schema Uniqueness
In XML Schema Definition (XSD), the xs:key and
xs:keyref elements establish identity constraints and
relational integrity within an XML document. While xs:key
guarantees that a specific value or combination of values is unique and
always present within a defined scope, xs:keyref acts as a
foreign key constraint, ensuring that referenced values correspond
directly to an existing key. Together, these elements prevent duplicate
entries, enforce mandatory identification fields, and maintain valid
relationships between distinct XML nodes.
The Role of the
xs:key Element
The xs:key element enforces strict uniqueness and
non-nullability for specified elements or attributes. Unlike the simpler
xs:unique element, which permits elements to have empty or
missing values, xs:key requires that every target item must
exist and contain a unique value within the specified scope.
An xs:key definition consists of two main child
elements: * xs:selector: Uses an XPath
expression to define the set of elements (the scope) to which the
constraint applies. * xs:field: Uses an
XPath expression to specify the exact element or attribute whose value
must be unique and present.
By supporting multi-field definitions, xs:key also
enables compound keys, allowing uniqueness to be determined by a
combination of multiple attributes or child elements.
The Role of the
xs:keyref Element
The xs:keyref element enforces referential integrity by
establishing a dependency on a predefined xs:key or
xs:unique constraint. It ensures that a value appearing in
one part of an XML document corresponds to an existing, valid key
defined elsewhere in the document.
The xs:keyref element uses the refer
attribute to target the name of the corresponding
xs:key. Like xs:key, it uses
xs:selector and xs:field to locate the
referencing data. If an XML document contains a keyref
value that does not match an existing key, the schema
validator rejects the document as invalid, thereby preventing orphaned
records or broken references.
Key Differences from Legacy ID/IDREF
Before the introduction of xs:key and
xs:keyref, XML relied on xs:ID and
xs:IDREF derived from DTDs. The key and
keyref elements provide significant advantages:
- Scope Control:
IDvalues must be globally unique across the entire XML document, whereaskeycan be scoped to specific subtrees or parent elements. - Data Types:
IDvalues are restricted to non-numeric NCName strings, whereaskeyandkeyrefcan be applied to any XML Schema data type, such as integers, dates, or custom types. - Compound Keys:
keysupports multiple fields to evaluate uniqueness across combinations of values, which is impossible withID.
Through these mechanisms, xs:key and
xs:keyref provide robust, database-like primary and foreign
key constraints directly within XML Schema validation.