XML - XML Schema
What is an XML Schema?
An XML Schema defines the structure, content, and data types of an XML document. It acts like a blueprint to ensure the XML data is valid and correctly formatted.
The most commonly used schema language is XSD (XML Schema Definition).
Schema is used for:
-
To validate XML documents
-
To enforce rules for elements and attributes
-
To specify data types (string, integer, date, etc.)
-
To ensure consistency and correctness across XML files
Basic XML Schema Syntax
Example XML File:
<?xml version="1.0"?>
<student xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="student.xsd">
<name>Ravi</name>
<age>21</age>
</student>
Corresponding XML Schema (student.xsd
):
<?xml version="1.0"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
<xs:element name="student">
<xs:complexType>
<xs:sequence>
<xs:element name="name" type="xs:string" />
<xs:element name="age" type="xs:integer" />
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:schema>
Key Components of XML Schema:
Element | Description |
---|---|
xs:schema |
Root element of the schema |
xs:element |
Defines an element (name, type) |
xs:complexType |
Groups nested elements |
xs:sequence |
Specifies order of child elements |
xs:attribute |
Defines attributes (name, type, use) |
xs:simpleType |
Defines basic data types or restrictions |
Common XML Schema Data Types:
-
xs:string
-
xs:integer
-
xs:decimal
-
xs:boolean
-
xs:date
-
xs:time