An XML schema defines the structure of an XML document. Consider the following example:
While the above is a syntactically correct XML file, age is supposed to be an integer. XML Schema helps to specify the structure of an XML file, define data types, etc. Interestingly, XML Schema is also an XML file. Here is an example of XML Schema:
In the above example, the tag <xs:schema> identifies the file as an XML Schema. By the attribute xmlns:xs="http://www.w3.org/2001/XMLSchema", the namepace "xs" is defined as http://www.w3.org/2001/XMLSchema (which is the namespace for XML schema). The attribute targetNamespace specifies which namespace the XML names defined in the schema will belong to. The fragment, xmlns="http://www.cstrends.com" defines the default namespace. That is, if there is an XML tag name in the document without namespace designation, then default namespace will be assumed. The
All elements (tag names) in the XML file has to be defined in the Schema. The tag <xs:element> can be used for defining elements. First, the root element test is defined as a "complexType" that contains the sequence of of elements name and age. As you might have noticed name and age are simple elements. Schema defines name as of type "xs:string" and age as of type "xs:int".
XML Schema supports numerous simple data types as shown in the table below:
Data Type | Description |
---|---|
string | Character String |
int | Integer |
date | Calendar Date in YYYY-MM-DD format |
Please W3C Website for more information.
Complex Data Types may be defined as in above example as a combination of simple data types or complex data types.
Schema may be specified by using the attribute xsi:schemaLocation as shown below:
The attribute