XML Schema is commonly known as XML Schema Definition (XSD). It is used to describe and validate the structure and the content of XML data. XML schema defines the elements, attributes and data types. Schema element supports Namespaces. It is similar to a database schema that describes the data in a database.
You need to declare a schema in your XML document as follows −
The following example shows how to use schema −
The basic idea behind XML Schemas is that they describe the legitimate format that an XML document can take.
As we saw in the XML - Elements chapter, elements are the building blocks of XML document. An element can be defined within an XSD as follows −
You can define XML schema elements in the following ways −
Simple type element is used only in the context of the text. Some of the predefined simple types are: xs:integer, xs:boolean, xs:string, xs:date. For example −
A complex type is a container for other element definitions. This allows you to specify which child elements an element can contain and to provide some structure within your XML documents. For example −
In the above example, Address element consists of child elements. This is a container for other definitions, that allows to build a simple hierarchy of elements in the XML document.
With the global type, you can define a single type in your document, which can be used by all other references. For example, suppose you want to generalize the person and company for different addresses of the company. In such case, you can define a general type as follows −
Now let us use this type in our example as follows −
Instead of having to define the name and the company twice (once for Address1 and once for Address2), we now have a single definition. This makes maintenance simpler, i.e., if you decide to add "Postcode" elements to the address, you need to add them at just one place.
Attributes in XSD provide extra information within an element. Attributes have name and type property as shown below −