How does
XSD work?
This section describes through examples
Simple use of XML Schema.
XML documents can
reference DTD
or XML Schema.
A simple XML document:
Take a look at this XML .xml "Note":
<?xml version="1.0"?>
<note>
<to>Tove</to>
<from>Jani</from>
<heading>Reminder</heading>
<body>Don't forget me this weekend!</body>
</note>
DTD file
The following example is a DTD file called "note.dtd" that defines the element of the XML document above ("note.xml"):
<!ELEMENT note (to, from, heading, body)>
<!ELEMENT to (#PCDATA)>
<!ELEMENT from (#PCDATA)>
<!ELEMENT heading (#PCDATA)>
<!ELEMENT body (#PCDATA)>
Line 1 defines note elements as having four child elements: "to, from, heading, body."
Line 2-5 defines the type of to, from, heading, body element as "#PCDATA."
XML Schema
The following example is an XML Schema file called "note.xsd" that defines the element of the XML document above ("note.xml"):
<?xml version="1.0"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"
targetNamespace="http://www.w3cschools.com"
xmlns="http://www.w3cschools.com"
elementFormDefault="qualified">
<xs:element name="note">
<xs:complexType>
<xs:sequence>
<xs:element name="to" type="xs:string"/>
<xs:element name="from" type="xs:string"/>
<xs:element name="heading" type="xs:string"/>
<xs:element name="body" type="xs:string"/>
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:schema>
The note element is a composite type because it contains other child elements. O
ther elements (to, from, heading, body) are simple types because they do not contain other elements.
You'll learn more about composite types and simple types in the following sections.
A reference to the DTD
This file contains a reference to the DTD:
<?xml version="1.0"?>
<!DOCTYPE note SYSTEM
"//www.w3cschool.cn/dtd/note.dtd">
<note>
<to>Tove</to>
<from>Jani</from>
<heading>Reminder</heading>
<body>Don't forget me this weekend!</body>
</note>
A reference to XML Schema
This file contains a reference to XML Schema:
<?xml version="1.0"?>
<note
xmlns="http://www.w3cschools.com"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.w3cschools.com note.xsd">
<to>Tove</to>
<from>Jani</from>
<heading>Reminder</heading>
<body>Don't forget me this weekend!</body>
</note>
In the next section, we'll cover the schema elements of XML.