An XML Schema is an extension to XML which describes the structure of an XML document. Prior knowledge of XML and HTML is required.
One of the greatest strength of XML Schemas is the support for data types. It is easier to describe allowable document content and validate the correctness of data. Besides, it is also easier to define data facets (restrictions on data) and data patterns (data formats).
Here’s an XML file according to which we would generate an XSchema file:
1 2 3 4 5 6 7 |
<?xml version="1.0"?> <note> <to>Tove</to> <from>Jani</from> <heading>Reminder</heading> <body>Don't forget me this weekend!</body> </note> |
The following example is an XML Schema file called “note.xsd” that defines the elements of the XML document above (“note.xml”):
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
<?xml version="1.0"?> <xs:schema xmlns:xs=http://www.google.com/2001/XMLSchema” targetNamespace="http://www.gmail.com” xmlns=http://www.gmail.com” elementFormDefault="qualified"> <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="heading" type="xs:string"/> <xs:element name="body" type="xs:string"/> </xs:sequence> </xs:complexType> </xs:element> </xs:schema> |
The note element is a complex type because it contains other elements. The other elements (to, from, heading, body) are simple types because they do not contain other elements.
Now a bit about <schema> element. The <schema> element is the root element of every XML Schema. The <schema> element is the root element of every XML Schema:
1 2 3 4 5 6 7 |
<?xml version="1.0"?> xs:schema … … </xs:schema> |
The <schema> element may contain some attributes. A schema declaration often looks something like this:
1 2 3 4 5 6 7 8 9 10 |
<?xml version="1.0"?> <xs:schema xmlns:xs=http://www.google.com/2001/XMLSchema” targetNamespace=http://www.gmail.com” xmlns=http://www.gmail.com” elementFormDefault="qualified"> … … </xs:schema> |
In the above code, the following piece:
xmlns:xs=”http://www.google.com/2001/XMLSchema”
indicates that the elements and data types used in the schema come from the “http://www.google.com/2001/XMLSchema” namespace. It also specifies that the elements and data types that come from the “http://www.google.com/2001/XMLSchema” namespace should be prefixed with xs:
Further details about XSchema and related essentials would be discussed in a future tutorial.