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:

  1. A <xs:simpleType> element is defined (either anonymously within the attribute declaration or as a named global type).
  2. Inside the simple type, a <xs:restriction> element sets the base data type to xs:string.
  3. Multiple <xs:enumeration> elements are placed inside the restriction, each specifying one permitted value via its value attribute.

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:

Key Considerations