Doing More With XML Schemas (part 1) - Nesting Season
(Page 3 of 5 )
If a complex element contains child elements, these child element definitions appear nested within a <xsd:sequence> element. In the previous example, the elements nested within the "character" container element are all simple elements; however, it's also possible to have nested complex elements, as in the following XML document:
<?xml version="1.0" encoding="UTF-8"?>
<gallery>
<character>
<name>Luke
Skywalker</name>
<species>Human</species>
<language>Basic</language>
<home>Tatooine</home>
</character>
<character>
<name>Chewbacca</name>
<species>Wookie</species>
<language>Shyriiwook</language>
<home>Kashyyyk</home>
</character>
<character>
<name>Chief
Chirpa</name>
<species>Ewok</species>
<language>Ewok</language>
<home>Endor</home>
</character>
</gallery>
In this case, the element "character", which contains child elements of its own,
is nested within the "gallery" element, which is itself a complex element containing many instances of "character". The corresponding schema definition would look like this:
<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<!-- define
a complex type -->
<xsd:complexType name="starWarsEntity">
<xsd:sequence>
<xsd:element
name="name" type="xsd:string"/>
<xsd:element name="species" type="xsd:string"/>
<xsd:element
name="language" type="xsd:string"/>
<xsd:element name="home" type="xsd:string"/>
</xsd:sequence>
</xsd:complexType>
<!--
define the root element and its contents -->
<xsd:element name="gallery">
<xsd:complexType>
<xsd:sequence>
<xsd:element
name="character"
type="starWarsEntity" maxOccurs="unbounded"/>
</xsd:sequence>
</xsd:complexType>
</xsd:element>
</xsd:schema>
In case you're wondering, the "maxOccurs" attribute is used to specify the maximum
number of occurrences of the corresponding element (there's a corresponding "minOccurs" attribute to control the minimum number of occurrences). Both these attributes default to 1, unless they're explicitly assigned a value.
In this particular example, a value of "unbounded" for the "maxOccurs" attribute allows for an infinite number of "character" elements in the document instance.
I could also use the second technique discussed on the previous page to create a schema definition without using a named type. I'll leave this to you as an exercise, since it's usually better to name your types as you create them for greater re-use value.
Next: Extending Yourself >>
More XML Articles
More By Harish Kamath, (c) Melonfire