XML Schemas

What is XML schema?

  • XML schema defines the structure of an XML document.
  • A schema defines, list of elements, attributes used in XML documents and data type of these elements.
  • It is known as XSD.

XSD vs DTD

XSDDTD
Defines list, order, data types of elements and attributes.Defines list, order of elements and attributes.
Provides control over the elements and attributes used in XML documents.It does not provide control over elements and attributes.
XSD allows to create customized datatype.DTD does not allow to create customized datatype.
Syntax of XSD is similar to XML document.Syntax of DTD is different from XML document.
XSD allows to define restrictions on data.
For example: Define the content in a  document by using only integer data type.
DTD does not allows to define restrictions on data.

Declaring Elements in XSD

Syntax:
<xsd:element name =“elementname” type=“datatype” minOccurs = “notNegativeInteger” maxOccurs=“nonNegativeInteger | unbounded”/>

Where,
     name: Defines the element name

     type: Defines data type.

     minOccurs: If its value is zero, the use of element is optional and if its value is greater than zero, the use of element is compulsory, and should occur at least for specified number of times.

     maxOccurs: If value is set as unbounded, the use of element can appear any number of times in the XML document without any limitation.

Example : XSD for simple type elements using predefined datatypes

<xsd:element name=“CARNAME” TYPE=“xsd:string”/>
<xsd:element name=“COMPANYNAME” TYPE=“xsd:string”/>
<xsd:element name=“PRICE” TYPE=“xsd:positiveInteger”/>

XML document with simple type elements and associated XSD using creation of custom data type.

<EMPLOYEENAME>Surabhi</EMPLOYEENAME>
<EMPLOYEEPHONE>9800000000</EMPLOYEEPHONE>
<xsd:element name=“EMPLOYEENAME” TYPE=“xsd:string”/>
<xsd:element name=“EMPLOYEEPHONE” TYPE=“xsd:string”/>
     <xsd:simpleType name=“phoneno”>
     <xsd:restriction base=“xsd:string”>
          <xsd:length value=“15”/>
          <xsd:pattern value=“\d{3}-\d{6}”/>
     </xsd:restriction>
     </xsd:simpleType>


In above example, the XSD defines the custom data type “phoneno”.

The data type “phoneno” has restrictions as, it can hold predefined data type string and it should be 12 characters long and \d presents 'digits'.

Inbuilt characters classes commonly used in XSD.

ClassMethodMeaning
[0-9]\ dAny digit.
[\ f\ r\ t \ n \ v] \ sAny white space.
[A-Za-z0-9]\ wAny word character.
[^0-9] \ DNot a digit.
[^ \ f \ r \ t \ n\ v]\ SNot a White space.
[^A-Za-z0-9]\ WNot a word character.