XML schema is a language which is used for expressing constraint about XML documents. There are so many schema languages which are used now a days for example Relax- NG and XSD (XML schema definition).
An XML schema is used to define the structure of an XML document. It is like DTD but provides more control on XML structure.
An XML document is called "well-formed" if it contains the correct syntax. A well-formed and valid XML document is one which have been validated against Schema.
Visit http://www.xmlvalidation.com to validate the XML file against schema or DTD.
Let's create a schema file.
employee.xsd
<?xml version="1.0"?> <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" targetNamespace="http://www.rookienerd.com" xmlns="http://www.rookienerd.com" elementFormDefault="qualified"> <xs:element name="employee"> <xs:complexType> <xs:sequence> <xs:element name="firstname" type="xs:string"/> <xs:element name="lastname" type="xs:string"/> <xs:element name="email" type="xs:string"/> </xs:sequence> </xs:complexType> </xs:element> </xs:schema>
Let's see the xml file using XML schema or XSD file.
employee.xml
<?xml version="1.0"?> <employee xmlns="http://www.rookienerd.com" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.rookienerd.com employee.xsd"> <firstname>vimal</firstname> <lastname>jaiswal</lastname> <email>vimal@rookienerd.com</email> </employee>
<xs:element name="employee"> : It defines the element name employee.
<xs:complexType> : It defines that the element 'employee' is complex type.
<xs:sequence> : It defines that the complex type is a sequence of elements.
<xs:element name="firstname" type="xs:string"/> : It defines that the element 'firstname' is of string/text type.
<xs:element name="lastname" type="xs:string"/> : It defines that the element 'lastname' is of string/text type.
<xs:element name="email" type="xs:string"/> : It defines that the element 'email' is of string/text type.
There are two types of data types in XML schema.
The simpleType allows you to have text-based elements. It contains less attributes, child elements, and cannot be left empty.
The complexType allows you to hold multiple attributes and elements. It can contain additional sub elements and can be left empty.