How xs:unique Works in XML Schema (XSD)
The xs:unique constraint in an XML Schema (XSD) is used
to enforce that specific element or attribute values are unique across a
designated scope in an XML document. This article explains the purpose
of the xs:unique element, breaks down its core
components—xs:selector and
xs:field—demonstrates how it operates with code examples,
and highlights how it differs from other uniqueness constraints like
xs:key.
Understanding the Core Components
An xs:unique constraint is defined inside an element
declaration in an XML Schema. It relies on a restricted subset of XPath
to target and evaluate nodes using two mandatory sub-elements:
xs:selector: Defines the scope of the constraint. Itsxpathattribute selects the set of elements across which uniqueness must be maintained.xs:field: Defines the specific value that must be unique within the selected elements. Itsxpathattribute points to an attribute or child element relative to thexs:selector.
Syntax and Implementation Example
Consider an XML document containing a list of employees where each employee must have a unique ID number.
XML Schema Definition (XSD)
<xs:element name="company">
<xs:complexType>
<xs:sequence>
<xs:element name="employee" maxOccurs="unbounded">
<xs:complexType>
<xs:sequence>
<xs:element name="name" type="xs:string"/>
</xs:sequence>
<xs:attribute name="id" type="xs:integer"/>
</xs:complexType>
</xs:element>
</xs:sequence>
</xs:complexType>
<!-- Define the unique constraint -->
<xs:unique name="uniqueEmployeeId">
<xs:selector xpath="employee"/>
<xs:field xpath="@id"/>
</xs:unique>
</xs:element>Valid XML Document
<company>
<employee id="101">
<name>Alice</name>
</employee>
<employee id="102">
<name>Bob</name>
</employee>
</company>If a second <employee> element were introduced
with id="101", the XML validator would reject the document
due to a violation of the uniqueEmployeeId constraint.
Composite Keys
You can specify multiple xs:field elements within a
single xs:unique definition. This creates a composite
uniqueness constraint where the combination of all field values must be
unique.
<xs:unique name="uniqueFullName">
<xs:selector xpath="employee"/>
<xs:field xpath="firstName"/>
<xs:field xpath="lastName"/>
</xs:unique>Handling Missing
Values: xs:unique vs. xs:key
The primary distinction between xs:unique and
xs:key lies in how they handle missing values:
xs:unique: Allows the target field to be optional ornil. If an element does not contain the specified field, it does not violate the constraint. However, if the field is present, its value must be unique.xs:key: Requires the target field to always exist, be non-nil, and be unique. Missing fields result in a validation error.
Use xs:unique when a field is optional throughout your
XML dataset but must not contain duplicate values whenever it is
provided.