SyntaxStudy
Sign Up
XML XSD Simple Types and Facets
XML Beginner 1 min read

XSD Simple Types and Facets

XSD simple types are used to constrain the text content of elements and the values of attributes. The specification defines 19 primitive built-in types including xs:string, xs:boolean, xs:decimal, xs:float, xs:double, xs:dateTime, xs:date, xs:time, xs:duration, xs:anyURI, xs:QName, and xs:hexBinary. There are also derived built-in types such as xs:integer, xs:positiveInteger, xs:nonNegativeInteger, xs:long, xs:int, xs:short, xs:byte, xs:token, xs:normalizedString, and xs:NMTOKEN. Custom simple types are defined using with a child that specifies a base type and one or more constraining facets. Common facets include: minInclusive and maxInclusive for numeric and date ranges, minExclusive and maxExclusive for exclusive bounds, minLength/maxLength/length for string length, enumeration for allowed values, pattern for regular-expression matching, whiteSpace for whitespace normalization, totalDigits and fractionDigits for decimal precision. List and union types extend simple types further. A list type (xs:list) defines a whitespace-separated list of values, each conforming to an item type. A union type (xs:union) allows a value to conform to any one of several member types. These facilities make XSD's type system considerably more expressive than DTD attribute types and are widely used in data-centric XML applications such as financial messaging and configuration file formats.
Example
<?xml version="1.0" encoding="UTF-8"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">

    <!-- Restriction: string with length and pattern -->
    <xs:simpleType name="ISBNType">
        <xs:restriction base="xs:string">
            <xs:pattern value="\d{3}-\d-\d{3}-\d{5}-\d"/>
            <xs:length value="17"/>
        </xs:restriction>
    </xs:simpleType>

    <!-- Restriction: integer range -->
    <xs:simpleType name="YearType">
        <xs:restriction base="xs:integer">
            <xs:minInclusive value="1800"/>
            <xs:maxInclusive value="2100"/>
        </xs:restriction>
    </xs:simpleType>

    <!-- Restriction: decimal precision -->
    <xs:simpleType name="PriceType">
        <xs:restriction base="xs:decimal">
            <xs:minInclusive value="0"/>
            <xs:totalDigits value="8"/>
            <xs:fractionDigits value="2"/>
        </xs:restriction>
    </xs:simpleType>

    <!-- List type: whitespace-separated list of tokens -->
    <xs:simpleType name="TagListType">
        <xs:list itemType="xs:token"/>
    </xs:simpleType>

    <!-- Union type: integer or "unknown" -->
    <xs:simpleType name="FlexibleCount">
        <xs:union memberTypes="xs:nonNegativeInteger">
            <xs:simpleType>
                <xs:restriction base="xs:string">
                    <xs:enumeration value="unknown"/>
                </xs:restriction>
            </xs:simpleType>
        </xs:union>
    </xs:simpleType>

</xs:schema>