How XML Schema Facets Restrict Primitive Data Types

XML Schema Definition (XSD) uses facets to define constraints on primitive data types, ensuring data conforms to strict business rules and structural requirements. By applying facets such as length limits, numeric boundaries, regular expression patterns, and enumerations inside an xs:restriction element, developers can derive specialized, validated simple types from generic built-in primitives like xs:string, xs:integer, and xs:decimal.

Understanding Facets in XML Schema

A facet is an XML element that defines a specific aspect of a value space. When a simple type is derived by restriction from a base primitive type, facets set the boundaries of what constitutes valid data. Facets act as validation filters, rejecting any XML document whose element or attribute values violate the defined parameters.

Restricting String Data Types

Primitive string types (such as xs:string and xs:normalizedString) can hold arbitrary text. Facets allow you to constrain length, enforce specific values, or dictate exact formatting.

String Restriction Example

<xs:simpleType name="ProductCodeType">
  <xs:restriction base="xs:string">
    <xs:pattern value="[A-Z]{3}-[0-9]{4}"/>
  </xs:restriction>
</xs:simpleType>

<xs:simpleType name="StatusType">
  <xs:restriction base="xs:string">
    <xs:enumeration value="Pending"/>
    <xs:enumeration value="Approved"/>
    <xs:enumeration value="Rejected"/>
  </xs:restriction>
</xs:simpleType>

Restricting Integer and Numeric Data Types

Numeric types such as xs:integer, xs:int, xs:byte, and xs:decimal can be constrained by value range and digit counts.

Integer Restriction Example

<xs:simpleType name="AgeType">
  <xs:restriction base="xs:integer">
    <xs:minInclusive value="0"/>
    <xs:maxInclusive value="120"/>
  </xs:restriction>
</xs:simpleType>

<xs:simpleType name="QuantityType">
  <xs:restriction base="xs:positiveInteger">
    <xs:maxExclusive value="1000"/>
    <xs:totalDigits value="3"/>
  </xs:restriction>
</xs:simpleType>

Summary of Common Facet Compatibility

Facet Compatible Types Primary Use Case
minInclusive / maxInclusive Integers, Decimals, Dates Defining inclusive value ranges
minExclusive / maxExclusive Integers, Decimals, Dates Defining exclusive value boundaries
length / minLength / maxLength Strings, Lists, Binary data Controlling exact or bounded character counts
pattern Almost all simple types Enforcing structural regex patterns
enumeration Almost all simple types Limiting values to a defined list
totalDigits / fractionDigits Decimals, Integers Controlling numeric precision and scale

By applying these facets within custom simple type definitions, XML Schemas enforce rigorous data integrity at the parser level before the data reaches application logic.