XML Schema

Instead of using DTD we can use an XML Schema to validate an XML document.

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"
<element name="name">
<element name="first" type="string"/>
<element name="middle" type="string"/>
<element name="last" type="string"/>
<attribute name="title" type="string"/>

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"?>
xsi:schemaLocation="ThisThreadXMLSchema example.xsd"

More information on XML Schema in chapter five of Beginning XML by David Hunter et al. (Wrox).

No comments:

Post a Comment