XSD Introduction
Understanding XML Schema Definition basics
📋 What is XSD?
XSD (XML Schema Definition) is a language for defining the structure, content, and data types of XML documents. It validates XML data and ensures documents follow specific rules.
<!-- Simple XSD example -->
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
<xs:element name="message" type="xs:string"/>
</xs:schema>
Valid XML:
<message>Hello XSD!</message>
Key XSD Concepts
XSD provides powerful tools to define and validate XML documents. It ensures data integrity and consistency across applications.
Validation
Ensures XML follows defined rules
<xs:element name="age" type="xs:integer"/>
Data Types
Defines types like string, integer, date
<xs:element name="price" type="xs:decimal"/>
Structure
Defines element hierarchy and order
<xs:sequence>
<xs:element name="first"/>
<xs:element name="last"/>
</xs:sequence>
Constraints
Applies rules and restrictions
<xs:minInclusive value="0"/>
<xs:maxInclusive value="100"/>
🔹 Why Use XSD?
XSD offers several advantages over older validation methods like DTD. It provides stronger typing and better integration with modern applications.
Benefits of XSD:
- Data Type Support: Built-in types like integer, date, boolean
- Namespace Support: Works with XML namespaces
- Extensibility: Create custom data types
- XML Syntax: Written in XML itself
- Better Validation: More precise than DTD
🔹 Basic XSD Structure
Every XSD document starts with a schema element and defines the structure of XML documents.
<?xml version="1.0" encoding="UTF-8"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
<!-- Define a simple element -->
<xs:element name="note">
<xs:complexType>
<xs:sequence>
<xs:element name="to" type="xs:string"/>
<xs:element name="from" type="xs:string"/>
<xs:element name="message" type="xs:string"/>
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:schema>
Valid XML Document:
<note>
<to>John</to>
<from>Jane</from>
<message>Hello!</message>
</note>
🔹 XSD vs DTD
XSD is the modern replacement for DTD (Document Type Definition) with enhanced capabilities.
<!-- DTD (Old Way) -->
<!ELEMENT person (name, age)>
<!ELEMENT name (#PCDATA)>
<!ELEMENT age (#PCDATA)>
<!-- XSD (Modern Way) -->
<xs:element name="person">
<xs:complexType>
<xs:sequence>
<xs:element name="name" type="xs:string"/>
<xs:element name="age" type="xs:integer"/>
</xs:sequence>
</xs:complexType>
</xs:element>
🔹 Simple XSD Example
Here's a complete example showing how XSD validates an XML document.
<!-- book.xsd -->
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
<xs:element name="book">
<xs:complexType>
<xs:sequence>
<xs:element name="title" type="xs:string"/>
<xs:element name="author" type="xs:string"/>
<xs:element name="year" type="xs:integer"/>
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:schema>
Valid XML (book.xml):
<book>
<title>Learning XSD</title>
<author>John Doe</author>
<year>2024</year>
</book>