Skip to content

XML Schema Datatypes — Complete Guide to XSD Types

DodaTech Updated 2026-06-23 7 min read

In this tutorial, you'll learn about XML Schema Datatypes. We cover key concepts, practical examples, and best practices.

XML Schema (XSD) datatypes define the allowed values and structure of elements and attributes in XML documents, providing a powerful type system that includes strings, numbers, dates, and custom derived types with constraining facets.

What You'll Learn

  • The built-in primitive and derived datatypes in XSD
  • How to restrict types using facets like minLength, maxInclusive, and pattern
  • Creating custom simple and complex types
  • Real-world schema patterns for enterprise validation

Why XSD Datatypes Matter

Without a type system, XML data validation is limited to checking structure. With XSD datatypes, you can ensure a price element contains a valid decimal, a date follows ISO 8601 format, or an email matches a regex pattern. This prevents data corruption at the point of entry — critical for financial systems, healthcare records, and configuration files. Durga Antivirus Pro uses XSD schemas with custom datatypes to validate malware signature XML files before processing them in the scan engine.

Learning Path

flowchart LR
  A[XML Basics] --> B[XPath Queries]
  B --> C[XSLT Transformations]
  C --> D[XSD Datatypes
You are here] D --> E[SOAP & WSDL]

Built-in Primitive Datatypes

XSD provides over 40 built-in datatypes. The most important primitives are:

Datatype Example Description
string "Hello World" Character strings
boolean true, false True/false values
decimal 12.99 Arbitrary precision numbers
integer 42 Whole numbers
date 2026-06-23 Calendar date (YYYY-MM-DD)
time 14:30:00 Time of day (HH:MM:SS)
dateTime 2026-06-23T14:30:00 Date and time combined
anyURI https://doda.tech URI or URL references

These primitives are the building blocks for all other XSD types.

Derived Datatypes

XSD derives more specific types from primitives using constraining facets:

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

    <!-- Positive integer — derived from integer -->
    <xs:simpleType name="positiveInt">
        <xs:restriction base="xs:integer">
            <xs:minInclusive value="1"/>
        </xs:restriction>
    </xs:simpleType>

    <!-- String with length restriction -->
    <xs:simpleType name="usStateCode">
        <xs:restriction base="xs:string">
            <xs:length value="2"/>
        </xs:restriction>
    </xs:simpleType>

    <!-- Email pattern -->
    <xs:simpleType name="emailType">
        <xs:restriction base="xs:string">
            <xs:pattern value="[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}"/>
        </xs:restriction>
    </xs:simpleType>

    <!-- Enumeration of allowed values -->
    <xs:simpleType name="currencyCode">
        <xs:restriction base="xs:string">
            <xs:enumeration value="USD"/>
            <xs:enumeration value="EUR"/>
            <xs:enumeration value="GBP"/>
            <xs:enumeration value="JPY"/>
        </xs:restriction>
    </xs:simpleType>

</xs:schema>

Explanation of Facets

Facet Applies To Effect
minLength / maxLength string types Limit character count
length string types Exact character count
minInclusive / maxInclusive numeric types Inclusive range bounds
minExclusive / maxExclusive numeric types Exclusive range bounds
pattern string types Regex validation
enumeration any simple type Whitelist of allowed values
totalDigits / fractionDigits decimal Precision control

Complex Types

Complex types describe elements that contain child elements or attributes:

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

    <!-- Complex type with sequence -->
    <xs:complexType name="bookType">
        <xs:sequence>
            <xs:element name="title" type="xs:string"/>
            <xs:element name="author" type="xs:string"/>
            <xs:element name="year" type="xs:gYear"/>
            <xs:element name="price" type="priceType"/>
        </xs:sequence>
        <xs:attribute name="category" type="xs:string" use="required"/>
        <xs:attribute name="id" type="xs:ID" use="optional"/>
    </xs:complexType>

    <!-- Complex type with mixed content -->
    <xs:complexType name="priceType">
        <xs:simpleContent>
            <xs:extension base="xs:decimal">
                <xs:attribute name="currency" type="currencyCode" use="required"/>
            </xs:extension>
        </xs:simpleContent>
    </xs:complexType>

    <!-- Using the types -->
    <xs:element name="library">
        <xs:complexType>
            <xs:sequence>
                <xs:element name="book" type="bookType" maxOccurs="unbounded"/>
            </xs:sequence>
        </xs:complexType>
    </xs:element>

</xs:schema>

Complex types fall into three categories:

  • Sequence: Child elements appear in a specific order
  • Choice: Exactly one child from a set of options
  • All: Child elements can appear in any order (max one each)

Using XSD to Validate XML

Here is a complete XML document validated against an XSD schema:

<?xml version="1.0" encoding="UTF-8"?>
<library>
    <book category="fiction" id="b1">
        <title>The Hobbit</title>
        <author>J.R.R. Tolkien</author>
        <year>1937</year>
        <price currency="USD">12.99</price>
    </book>
    <book category="non-fiction" id="b2">
        <title>A Brief History of Time</title>
        <author>Stephen Hawking</author>
        <year>1988</year>
        <price currency="GBP">9.99</price>
    </book>
</library>

XSD Instance Declaration

The XML document references the schema:

<?xml version="1.0" encoding="UTF-8"?>
<library
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:noNamespaceSchemaLocation="library.xsd">
    <!-- book elements here -->
</library>

Facet Combinations in Practice

XSD facets combine to create precise data constraints:

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

    <!-- Password: 8-20 chars, at least one number and special char -->
    <xs:simpleType name="passwordType">
        <xs:restriction base="xs:string">
            <xs:minLength value="8"/>
            <xs:maxLength value="20"/>
            <xs:pattern value="(?=.*\d)(?=.*[!@#$%^&*]).{8,20}"/>
        </xs:restriction>
    </xs:simpleType>

    <!-- Product code: two letters followed by four digits -->
    <xs:simpleType name="productCode">
        <xs:restriction base="xs:string">
            <xs:pattern value="[A-Z]{2}\d{4}"/>
        </xs:restriction>
    </xs:simpleType>

    <!-- Rating: 1.0 to 5.0 in 0.5 increments -->
    <xs:simpleType name="ratingType">
        <xs:restriction base="xs:decimal">
            <xs:minInclusive value="1.0"/>
            <xs:maxInclusive value="5.0"/>
            <xs:fractionDigits value="1"/>
        </xs:restriction>
    </xs:simpleType>

    <!-- ISBN-13: exactly 13 digits, optional hyphens -->
    <xs:simpleType name="isbn13">
        <xs:restriction base="xs:string">
            <xs:pattern value="\d{3}-?\d{1}-?\d{4}-?\d{4}-?\d{1}"/>
        </xs:restriction>
    </xs:simpleType>

</xs:schema>

Real-World Use: Configuration Validation

Doda Browser uses XSD schemas to validate browser configuration profiles:

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

    <xs:simpleType name="nonNegativeInt">
        <xs:restriction base="xs:integer">
            <xs:minInclusive value="0"/>
        </xs:restriction>
    </xs:simpleType>

    <xs:complexType name="proxyConfig">
        <xs:sequence>
            <xs:element name="host" type="xs:string"/>
            <xs:element name="port" type="xs:integer">
                <xs:annotation>
                    <xs:documentation>Port must be 1-65535</xs:documentation>
                </xs:annotation>
            </xs:element>
            <xs:element name="useAuthentication" type="xs:boolean"/>
            <xs:element name="username" type="xs:string" minOccurs="0"/>
            <xs:element name="password" type="xs:string" minOccurs="0"/>
        </xs:sequence>
    </xs:complexType>

    <xs:element name="browserConfig">
        <xs:complexType>
            <xs:sequence>
                <xs:element name="homepage" type="xs:anyURI"/>
                <xs:element name="maxTabs" type="nonNegativeInt"/>
                <xs:element name="proxy" type="proxyConfig" minOccurs="0"/>
                <xs:element name="blockedDomains" minOccurs="0">
                    <xs:complexType>
                        <xs:sequence>
                            <xs:element name="domain" type="xs:string" maxOccurs="unbounded"/>
                        </xs:sequence>
                    </xs:complexType>
                </xs:element>
            </xs:sequence>
        </xs:complexType>
    </xs:element>

</xs:schema>

This schema ensures every browser configuration file has a valid homepage URL, a non-negative maxTabs count, and optional proxy settings with proper port numbers.

Security Angle

XSD validation prevents injection attacks by enforcing data shapes at the schema level. Durga Antivirus Pro validates all XML-based threat signature files against a strict XSD before loading them. If a signature file contains unexpected elements or malformed data types, the parser rejects it immediately — preventing XXE and entity expansion attacks that often arrive disguised as malformed signature updates.

Common Mistakes

1. Forgetting the target namespace

<!-- Wrong: missing targetNamespace -->
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
<!-- Correct: declare targetNamespace -->
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"
           targetNamespace="http://books.example.com">

2. Confusing minOccurs/maxOccurs with minLength/maxLength

minOccurs controls how many times an element appears in a parent. minLength controls the character count of a string. They belong to different categories.

3. Using choice when you need sequence

xs:choice means exactly one of the options. xs:sequence means all in order. Mixing them up causes false validation failures.

4. Not specifying use="required" on mandatory attributes

By default, attributes are optional. If an attribute must always be present, set use="required".

Practice Questions

  1. What is the difference between xs:simpleType and xs:complexType? A simple type can only contain text values (optionally restricted by facets). A complex type can contain child elements and attributes.

  2. What does the xs:pattern facet do? It restricts a string value to match a regular expression pattern, like [A-Z]{2}\d{4} for a product code.

  3. How do you make an attribute required in XSD? Set use="required" inside the xs:attribute element. By default, attributes are optional.

Challenge: Design an XSD schema for an employee database that includes name (string), email (validated pattern), salary (decimal between 0 and 999999.99 with 2 fraction digits), department (enumeration of Sales, Engineering, HR), and an optional manager ID reference.

FAQ

What is an XSD datatype?

An XSD datatype defines the allowed values for an element or attribute, including built-in types like string and integer and custom types created with facets.

What is the difference between XSD and DTD?

XSD uses XML syntax, supports datatypes and namespaces, and is more powerful. DTD uses its own syntax, has no type system beyond text, and lacks namespace support.

What facets can restrict an XSD string?

minLength, maxLength, length, pattern, enumeration, and whiteSpace are the primary facets for string types.

Can XSD validate numeric ranges?

Yes. Use minInclusive, maxInclusive, minExclusive, and maxExclusive on numeric types like decimal and integer.

What is the difference between xs:sequence and xs:all?

xs:sequence requires child elements in a specific order. xs:all allows them in any order but limits each child to one occurrence.

How do I reference an XSD schema from an XML file?

Use the xsi:schemaLocation or xsi:noNamespaceSchemaLocation attributes on the root element.

Try It Yourself

Validate an XML file against an XSD schema using Python:

from lxml import etree

# Load schema
xsd_doc = etree.parse("library.xsd")
xsd_schema = etree.XMLSchema(xsd_doc)

# Load XML
xml_doc = etree.parse("library.xml")

# Validate
if xsd_schema.validate(xml_doc):
    print("XML document is valid against the schema.")
else:
    print("Validation errors:")
    for error in xsd_schema.error_log:
        print(f"  Line {error.line}: {error.message}")

# Expected output (valid):
# XML document is valid against the schema.

# Expected output (invalid):
# Validation errors:
#   Line 5: Element 'year': '19xy' is not a valid value of type 'gYear'.

What's Next

Tutorial What You'll Learn
XPath Explained — Querying XML Navigate XML documents with path expressions
XSLT Explained — Transform XML Transform XML into HTML and other formats
XML Parsing in Python Process XML with Python's ElementTree and lxml

Built by the developers of Doda Browser, DodaZIP, and Durga Antivirus Pro. Updated 2026-06-23.

What's Next

Congratulations on completing this XSD Datatypes tutorial! Here's where to go from here:

  • Practice daily — Consistency is more important than long study sessions
  • Build a project — Create an XSD schema for a real data format
  • Explore related topics — Check out other XML tutorials in this category
  • Join the community — Discuss with other learners and share your progress

Remember: every expert was once a beginner. Keep coding!

Built by the developers of DodaTech

Doda Browser, DodaZIP & Durga Antivirus Pro