XSD Validation
Estimated study time: 12 minutes.
Validation is the process of checking whether an XML document conforms to the rules defined in its XSD schema — correct elements, correct types, correct order, and correct constraints.
How Validation Works
A parser reads both the XML document and its referenced XSD, then checks the document against the schema's rules. If anything doesn't match — a missing required element, wrong data type, invalid attribute value — validation fails with a specific error.
Adding Constraints with Facets
<xs:simpleType name="seatCount">
<xs:restriction base="xs:integer">
<xs:minInclusive value="1"/>
<xs:maxInclusive value="60"/>
</xs:restriction>
</xs:simpleType>
This restricts a numeric value to a specific range. Other common facets include pattern (regular expression matching), minLength/maxLength, and enumeration.
Pattern Example
<xs:simpleType name="courseId">
<xs:restriction base="xs:string">
<xs:pattern value="[A-Z]{2}-[0-9]{3}"/>
</xs:restriction>
</xs:simpleType>
This forces values like DA-101 to match the pattern, rejecting anything that doesn't fit.
Why Validation Matters
- Catches bad data before it reaches downstream systems or databases.
- Provides a clear, shared contract between systems exchanging XML.
- Reduces the need for manual data-checking code in your application.