Designing Your Own XML Schema: Indicators - The maxOccurs and minOccurs indicators in XML Schema
(Page 4 of 6 )
I have already explained a bit about those two indicators in my previous articles. Now, we shall see them in more depth.
The “maxOccurs” indicator indicates the number of times an element can repeat itself. If you do not specify (or forget to specify) this indicator, it defaults to “1.” That means your XML document could contain only one occurrence of that element (with respect to its parent element).
If you are unaware of the maximum number of elements expected, then you can specify a value as “unbounded.” When you specify “unbounded,” it would permit any number of elements.
Similarly, we have “minOccurs.” It indicates what number of copies of the same element MUST present (with respect to its parent element). If you do not specify (or forget to specify) this indicator, it defaults to “1.” That means you must include the element in your XML document.
Let us consider the following XML Schema:
<?xml version="1.0" encoding="UTF-8"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"
elementFormDefault="qualified"
attributeFormDefault="unqualified">
<xs:element name="Employees">
<xs:annotation>
<xs:documentation>Contains All Employee
information</xs:documentation>
</xs:annotation>
<xs:complexType>
<xs:sequence>
<xs:element name="Employee"
maxOccurs="unbounded">
<xs:complexType>
<xs:sequence>
<xs:element name="ID"
type="xs:string" />
<xs:element name="Name"
type="xs:string" />
<xs:element name="Address"
type="xs:string" maxOccurs="unbounded" minOccurs="1" />
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:sequence>
</xs:complexType>
<xs:key name="PK_Employee_ID">
<xs:selector xpath=".//Employee" />
<xs:field xpath="ID" />
</xs:key>
</xs:element>
</xs:schema>
The most important fragment to concentrate on is the following:
<xs:element name="Address" type="xs:string" maxOccurs="unbounded"
minOccurs="1" />
The above specifies that the “Address” element can be repeated any number of times within the “Employee” element and should be available at least once. A sample XML document, which conforms to the above schema, would be as follows:
<?xml version="1.0" encoding="UTF-8"?>
<Employees xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="C:\Documents and
Settings\Administrator\Desktop\Employees.xsd">
<Employee>
<ID>1001</ID>
<Name>Jag</Name>
<Address>13-20-26, Nallam vari thota, Gunupudi,
Bhimavaram-534201</Address>
<Address>1111, another street, another city, another city
and pincode</Address>
</Employee>
</Employees>
Next: Groups in XML Schema >>
More XML Articles
More By Jagadish Chaterjee