Creating an XML Schema(.xsd) from and XML Document(.xml)

XSD (XML Schema Definition), a recommendation of the World Wide Web Consortium (W3C), specifies how to formally describe the elements in an Extensible Markup Language (XML) document. It can be used by programmers to verify each piece of item content in a document.

This is a simple tutorial for creating an XML schema(XSD) for an XML document. The image shows the hierarchy of elements. This hierarchy would help you to understand the structure of this XML document and make it easier for you to write an XSD.

Hierarchy of Elements in XML document (department.xml)
Hierarchy of Elements in XML document (department.xml)

It is recommended that you always follow this practice of creating a hierarchy of elements/tags before making XSD for an XML.

Following is a simple XML file show data about a department of an institute and its students.

department.xml

<?xml version=”1.0″ encoding=”utf-8″?>
<department>

<department_name>software engineering</department_name>
<institute_name>mehran UET</institute_name>
<location>jamshoro</location>

<student>
<name>Azhar</name>
<rollno>112233</rollno>
<batch>2014</batch>
</student>
<student>
<name>faisal</name>
<rollno>112244</rollno>
<batch>2013</batch>
</student>

</department>

Every root element(department and student) shown in the diagram is interpreted as complex type in XSD.

Here is the corresponding XSD for the above XML:

department.xsd

<xs:schema xmlns:xs=”http://www.w3.org/2001/XMLSchema”&gt;
<xs:element name=”department”>
<xs:complexType>
<xs:sequence>
<xs:element type=”xs:string” name=”department_name”/>
<xs:element type=”xs:string” name=”institute_name”/>
<xs:element type=”xs:string” name=”location”/>
<xs:element name=”student” maxOccurs=”unbounded” minOccurs=”0″>
<xs:complexType>
<xs:sequence>
<xs:element type=”xs:string” name=”name”/>
<xs:element type=”xs:int” name=”rollno”/>
<xs:element type=”xs:short” name=”batch”/>
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:schema>

Try this one and then try creating your own XMLs  and their XSDs.

For checking if you have created a correct XML and XSD, use this link:

http://www.freeformatter.com/xml-validator-xsd.html.

Online XML and XSD validator
Online XML and XSD validator

This is an online validator. Copy and paste the XML document and XSD to check the results.

Thank You.

Code On! 😀