XSD Restrictions/Facets

Welcome to The Coding College! In this tutorial, we’ll dive into XSD Restrictions/Facets, which allow you to control the values and structure of simple elements and attributes in XML documents. By applying restrictions, you can ensure your XML data adheres to specific rules, improving its reliability and consistency.

What are XSD Restrictions/Facets?

Restrictions, also known as facets, are rules that constrain the value space of XML elements or attributes. They allow you to:

  • Define value ranges.
  • Enforce lengths or patterns.
  • Specify enumerations for valid values.

Restrictions are applied to simple types in an XSD schema using the <xs:restriction> element.

Commonly Used Facets

Here are some of the most widely used XSD facets:

FacetDescription
enumerationDefines a list of acceptable values.
patternSpecifies a regular expression that the value must match.
lengthRequires the value to have an exact length.
minLengthSets a minimum length for the value.
maxLengthSets a maximum length for the value.
minInclusiveSpecifies the minimum allowed value (inclusive).
maxInclusiveSpecifies the maximum allowed value (inclusive).
minExclusiveSpecifies the minimum allowed value (exclusive).
maxExclusiveSpecifies the maximum allowed value (exclusive).
fractionDigitsLimits the number of fractional digits for decimal numbers.
totalDigitsSets the total number of digits allowed for a numeric value.
whiteSpaceControls how white space is handled (e.g., preserve, replace, collapse).

Defining Restrictions in XSD

To define a restriction, you:

  1. Use the <xs:simpleType> element to define a custom data type.
  2. Use the <xs:restriction> element to apply facets to a base type.

Syntax:

<xs:simpleType>
  <xs:restriction base="xs:dataType">
    <xs:facetName value="facetValue"/>
  </xs:restriction>
</xs:simpleType>

Examples of XSD Restrictions

Example 1: Restricting Values with enumeration

<xs:element name="status">
  <xs:simpleType>
    <xs:restriction base="xs:string">
      <xs:enumeration value="active"/>
      <xs:enumeration value="inactive"/>
      <xs:enumeration value="pending"/>
    </xs:restriction>
  </xs:simpleType>
</xs:element>

Explanation:

  • The status element can only have one of the values: active, inactive, or pending.

Corresponding XML Document:

<status>active</status>

Example 2: Restricting Length with length, minLength, and maxLength

<xs:element name="zipCode">
  <xs:simpleType>
    <xs:restriction base="xs:string">
      <xs:length value="5"/>
    </xs:restriction>
  </xs:simpleType>
</xs:element>

Explanation:

  • The zipCode element must be exactly 5 characters long.

Corresponding XML Document:

<zipCode>12345</zipCode>

Example 3: Restricting Numeric Ranges with minInclusive and maxInclusive

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

Explanation:

  • The age element must be an integer between 0 and 120 (inclusive).

Corresponding XML Document:

<age>25</age>

Example 4: Defining Patterns with pattern

<xs:element name="phoneNumber">
  <xs:simpleType>
    <xs:restriction base="xs:string">
      <xs:pattern value="\d{3}-\d{3}-\d{4}"/>
    </xs:restriction>
  </xs:simpleType>
</xs:element>

Explanation:

  • The phoneNumber element must follow the pattern XXX-XXX-XXXX where X is a digit.

Corresponding XML Document:

<phoneNumber>123-456-7890</phoneNumber>

Example 5: Restricting Decimal Values with totalDigits and fractionDigits

<xs:element name="price">
  <xs:simpleType>
    <xs:restriction base="xs:decimal">
      <xs:totalDigits value="6"/>
      <xs:fractionDigits value="2"/>
    </xs:restriction>
  </xs:simpleType>
</xs:element>

Explanation:

  • The price element can have up to 6 digits in total and 2 fractional digits (e.g., 1234.56).

Corresponding XML Document:

<price>99.99</price>

Example 6: Handling White Space with whiteSpace

<xs:element name="text">
  <xs:simpleType>
    <xs:restriction base="xs:string">
      <xs:whiteSpace value="collapse"/>
    </xs:restriction>
  </xs:simpleType>
</xs:element>

Explanation:

  • The whiteSpace facet with the collapse value removes leading and trailing spaces and reduces multiple spaces to a single space.

Corresponding XML Document:

<text>    Hello    World   </text>
<!-- Interpreted as: "Hello World" -->

Combining Multiple Facets

You can combine multiple facets to apply complex restrictions.

Example 7: Combining Facets

<xs:element name="password">
  <xs:simpleType>
    <xs:restriction base="xs:string">
      <xs:minLength value="8"/>
      <xs:maxLength value="20"/>
      <xs:pattern value="[A-Za-z0-9@#$%^&+=]+"/>
    </xs:restriction>
  </xs:simpleType>
</xs:element>

Explanation:

  • The password element must:
    • Be between 8 and 20 characters long.
    • Contain only alphanumeric characters and special symbols @, #, $, %, ^, &, +, =.

Corresponding XML Document:

<password>Pass@123</password>

Practical Example: XML Schema with Restrictions

XML Document

<user>
  <username>john_doe</username>
  <age>30</age>
  <email>[email protected]</email>
</user>

XSD File

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

  <xs:element name="user">
    <xs:complexType>
      <xs:sequence>
        <xs:element name="username">
          <xs:simpleType>
            <xs:restriction base="xs:string">
              <xs:minLength value="5"/>
              <xs:maxLength value="15"/>
            </xs:restriction>
          </xs:simpleType>
        </xs:element>
        <xs:element name="age">
          <xs:simpleType>
            <xs:restriction base="xs:integer">
              <xs:minInclusive value="18"/>
              <xs:maxInclusive value="100"/>
            </xs:restriction>
          </xs:simpleType>
        </xs:element>
        <xs:element name="email">
          <xs:simpleType>
            <xs:restriction base="xs:string">
              <xs:pattern value="[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}"/>
            </xs:restriction>
          </xs:simpleType>
        </xs:element>
      </xs:sequence>
    </xs:complexType>
  </xs:element>

</xs:schema>

Best Practices for Using Facets

  1. Choose Specific Facets: Use facets like pattern and enumeration to enforce strict validation.
  2. Combine Facets Wisely: Combine multiple restrictions for comprehensive control over values.
  3. Test Validation: Always test your schema against sample XML data to ensure it behaves as expected.

Conclusion

XSD restrictions or facets are powerful tools for validating and constraining XML data. By mastering them, you can enforce rules that ensure your XML documents are accurate and consistent.

Leave a Comment