Understanding XML Schema - Nesting Season
(Page 6 of 12 )
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 "movie" 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"?>
<movie>
<title>Moulin Rouge</title>
<cast>
<person>Nicole
Kidman</person>
<person>Ewan McGregor</person>
</cast>
</movie>
In this case, the element "cast", which contains child elements of its own, is
nested within the "movie" element, which is itself a complex element. The corresponding schema definition would look like this:
<?xml version"1.0"?>
<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<xsd:element
name="movie">
<xsd:complexType>
<xsd:sequence>
<!-- simple element
definition -->
<xsd:element name="title" type="xsd:string"/>
<!--
complex element definition -->
<xsd:element name="cast">
<xsd:complexType>
<xsd:sequence>
<xsd:element
name="person" type="xsd:string" maxOccurs="unbounded"/>
</xsd:sequence>
</xsd:complexType>
</xsd:element>
</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. And just incidentally, you can't achieve this level of precision with a DTD.
In this particular example, a value of "unbounded" for the "maxOccurs" attribute allows for an infinite number of "person" elements in the document instance.
It's also possible to make certain elements optional. In order to illustrate this, let's add a couple of new elements to the schema definition above - a "release_date" element of type "date", and a "rating" element of type "integer". And let's also make the "release_date" element optional, through judicious use of the "minOccurs" and "maxOccurs" attributes.
<?xml version"1.0"?>
<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<xsd:element
name="movie">
<xsd:complexType>
<xsd:sequence>
<!-- simple element
definition -->
<xsd:element name="title" type="xsd:string"/>
<!--
complex element definition -->
<xsd:element name="cast">
<xsd:complexType>
<xsd:sequence>
<xsd:element
name="person" type="xsd:string" maxOccurs="unbounded"/>
</xsd:sequence>
</xsd:complexType>
</xsd:element>
<!--
simple element definition -->
<xsd:element name="release_date" type="xsd:date"
maxOccurs="1"
minOccurs="0"/>
<!-- simple element definition -->
<xsd:element
name="rating" type="xsd:integer"/>
</xsd:sequence>
</xsd:complexType>
</xsd:element>
</xsd:schema>
Next: Battle Of The Sexes >>
More XML Articles
More By Harish Kamath, (c) Melonfire