Pages

XSD global and local elements

In an XML Schema we could specify an element creating a local type, using a global type, or referencing to an already existing global type.

The elements declared as direct children of the "schema" element are implicitly global. All the element declared as children of other than the "schema" element are local and could be used only in that context.

In the first XSD we have written we have a global element, name, and three local ones, children of name.

We can make all the elements global, and using the required ones in "name" by reference:

<?xml version="1.0" encoding="UTF-8"?>
<schema xmlns="http://www.w3.org/2001/XMLSchema"
xmlns:target="ThisThreadXMLSchema"
targetNamespace="ThisThreadXMLSchema"
elementFormDefault="qualified">
<element name="first" type="string"/>
<element name="middle" type="string"/>
<element name="last" type="string"/>
<element name="name">
<complexType>
<sequence>
<element ref="target:first"/>
<element ref="target:middle"/>
<element ref="target:last"/>
</sequence>
<attribute name="title" type="string"/>
</complexType>
</element>
</schema>

We can extract the complex type from the "name" element definition, put it under "schema", and then using it as "type" for the "name" element definition:

<?xml version="1.0" encoding="UTF-8"?>
<schema xmlns="http://www.w3.org/2001/XMLSchema"
xmlns:target="ThisThreadXMLSchema"
targetNamespace="ThisThreadXMLSchema"
elementFormDefault="qualified">
<element name="first" type="string"/>
<element name="middle" type="string"/>
<element name="last" type="string"/>
<complexType name="NameType">
<sequence>
<element ref="target:first"/>
<element ref="target:middle"/>
<element ref="target:last"/>
</sequence>
<attribute name="title" type="string"/>
</complexType>
<element name="name" type="target:NameType"/>
</schema>

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

No comments:

Post a Comment