DTD is still popular, and the best choice for some case, but, as we are going to see, XML Schema has a few relevant advantages that makes it worth to be used.
An XML can't be embedded in an XML document, but should be stored in a standalone file, usually identified by the xsd extension.
Here is an XSD that defines an XML with a root element, "name", having an attribute, "title", and a sequence of three contained elements:
<?xml version="1.0" encoding="UTF-8"?>
<schema xmlns="http://www.w3.org/2001/XMLSchema"
xmlns:target="ThisThreadXMLSchema"
targetNamespace="ThisThreadXMLSchema"
elementFormDefault="qualified">
<element name="name">
<complexType>
<sequence>
<element name="first" type="string"/>
<element name="middle" type="string"/>
<element name="last" type="string"/>
</sequence>
<attribute name="title" type="string"/>
</complexType>
</element>
</schema>
The root attribute should be defined after the sequence of elements in it. It is not mandatory, so could be present or not in our XML.
On the other side, first, middle and last are in a sequence, so all three of them should be in the XML, in that specified order.
Here is the example of a valid XML for the specified XSD (saved in the same directory with name example.xsd):
<?xml version="1.0" encoding="UTF-8"?>
<name
xmlns="ThisThreadXMLSchema"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="ThisThreadXMLSchema example.xsd"
title="Mr.">
<first>John</first>
<middle>Fearless</middle>
<last>Smith</last>
</name>
More information on XML Schema in chapter five of Beginning XML by David Hunter et al. (Wrox).
No comments:
Post a Comment