Re: recursive relationship in XML schema

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 UTC