W3C home > Mailing lists > Public > xmlschema-dev@w3.org > March 2002

Re: recursive relationship in XML schema

From: Jeni Tennison <jeni@jenitennison.com>
Date: Wed, 27 Mar 2002 11:49:33 +0000
Message-ID: <125394981613.20020327114933@jenitennison.com>
To: santy subramanian <santysemail@yahoo.com>
CC: xmlschema-dev@w3.org
Hi Santy,

> Is it possible to define a XML schema that allows for the following
> –
>
> A company can be made up department or employees. There must be at
> least one department or at least one employee in the company and a
> department must have at least one employee.

Yes. To have a recursive definition like this, you have to have global
declarations or definitions of the elements, types or content models
that you're using (or some combination of that).

One method would be to have global declarations of the elements, and
refer to those global declarations using the ref attribute on
xs:element from within the content models, as follows:

<xs:element name="department">
  <xs:complexType>
    <xs:choice>
      <xs:element ref="department" maxOccurs="unbounded" />
      <xs:element ref="employee" maxOccurs="unbounded" />
    </xs:choice>
    <xs:attribute name="name" type="xs:string" />
  </xs:complexType>
</xs:element>

<xs:element name="employee">
  <xs:complexType>
    <xs:attribute name="name" type="xs:string" />
  </xs:complexType>
</xs:element>

Another method would be to have named complex types that you refer to
when declaring the department and employee element. Note that this
technique means that the top-level department and the nested
departments are subtly different:

<xs:element name="department" type="department" />

<xs:complexType name="department">
  <xs:choice>
    <xs:element name="department" type="department" maxOccurs="unbounded" />
    <xs:element name="employee" type="employee" maxOccurs="unbounded" />
  </xs:choice>
  <xs:attribute name="name" type="xs:string" />
</xs:complexType>

<xs:complexType name="employee">
  <xs:attribute name="name" type="xs:string" />
</xs:complexType>

You can combine the two if you want, as well. The only method you
can't use for a recursive structure is a simple "Russian Doll"
approach where all the complex types are anonymous and all but the
top-level element is declared locally.

Cheers,

Jeni

---
Jeni Tennison
http://www.jenitennison.com/
Received on Wednesday, 27 March 2002 06:49:40 GMT

This archive was generated by hypermail 2.2.0+W3C-0.50 : Tuesday, 11 January 2011 00:14:30 GMT