How to Restrict Numeric Ranges in XML Schema

XML Schema Definition (XSD) allows you to enforce numeric ranges on child elements by deriving a custom xs:simpleType using facet restrictions. By applying constraints such as xs:minInclusive, xs:maxInclusive, xs:minExclusive, or xs:maxExclusive to a base numeric type like xs:integer or xs:decimal, you can ensure that the XML parser validates that child element values fall strictly within your defined boundaries.

Defining Range Facets

To constrain numeric values, XSD provides four primary facets:

Implementation Example

To enforce that a child element named <age> has an integer value between 1 and 120 (inclusive), define a custom simple type with xs:minInclusive and xs:maxInclusive:

<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">

  <!-- Define the restricted numeric simple type -->
  <xs:simpleType name="AgeRangeType">
    <xs:restriction base="xs:integer">
      <xs:minInclusive value="1"/>
      <xs:maxInclusive value="120"/>
    </xs:restriction>
  </xs:simpleType>

  <!-- Use the restricted type in a parent element -->
  <xs:element name="person">
    <xs:complexType>
      <xs:sequence>
        <xs:element name="name" type="xs:string"/>
        <xs:element name="age" type="AgeRangeType"/>
      </xs:sequence>
    </xs:complexType>
  </xs:element>

</xs:schema>

Inline Anonymous Type Definition

If the restriction is only needed for a single element, you can embed the xs:simpleType directly inside the element declaration:

<xs:element name="score">
  <xs:simpleType>
    <xs:restriction base="xs:decimal">
      <xs:minInclusive value="0.0"/>
      <xs:maxInclusive value="100.0"/>
    </xs:restriction>
  </xs:simpleType>
</xs:element>

Validation Behavior

When an XML processor validates an XML document against this schema: