How to Restrict XML Attributes with Enumeration Facets
In XML Schema Definition (XSD), enumeration facets limit the
acceptable values of an XML attribute by defining a strict, finite
whitelist of valid strings. By encapsulating xs:enumeration
elements within a xs:restriction base type, schema
designers can prevent arbitrary text entry and enforce strict data
consistency across XML documents. When an XML parser validates a
document against the schema, any attribute value not explicitly declared
in the enumeration list will trigger a validation error.
The Mechanism: Simple Types and Restrictions
XML attributes cannot contain child elements, so their values are always simple types. To constrain an attribute to a fixed list of strings:
- A
<xs:simpleType>element is defined (either anonymously within the attribute declaration or as a named global type). - Inside the simple type, a
<xs:restriction>element sets the base data type toxs:string. - Multiple
<xs:enumeration>elements are placed inside the restriction, each specifying one permitted value via itsvalueattribute.
Example Schema Definition
The following schema defines a <task> element with
a status attribute restricted to three values:
pending, in-progress, and
completed.
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
<xs:element name="task">
<xs:complexType>
<xs:attribute name="status" use="required">
<xs:simpleType>
<xs:restriction base="xs:string">
<xs:enumeration value="pending"/>
<xs:enumeration value="in-progress"/>
<xs:enumeration value="completed"/>
</xs:restriction>
</xs:simpleType>
</xs:attribute>
</xs:complexType>
</xs:element>
</xs:schema>Validation Behavior
During validation, the XML parser compares the string value inside the XML instance document against the defined enumeration list:
Valid XML:
<task status="in-progress"/>The value
in-progressmatches one of the definedxs:enumerationentries, so validation succeeds.Invalid XML:
<task status="archived"/>The value
archivedis not present in the enumeration list, causing the validating parser to reject the document with a schema violation error.
Key Considerations
- Case Sensitivity: String enumerations in XSD are
strictly case-sensitive. If an enumeration specifies
pending, providingPendingorPENDINGwill cause a validation failure unless those variations are also explicitly declared as separate enumerations. - Whitespace Handling: By default, base type
xs:stringpreserves whitespace. When combined with enumerations, leading or trailing whitespace that does not match the exact enumeration value will cause validation to fail. - Reusability: Defining the enumeration as a named
global
<xs:simpleType>allows the same fixed list to be reused across multiple attributes and elements throughout the schema.