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

Re: Generic Question

From: Jeni Tennison <jeni@jenitennison.com>
Date: Tue, 4 Mar 2003 10:55:33 +0000
Message-ID: <14403423412.20030304105533@jenitennison.com>
To: Shirish Kulkarni <shirish_kul@yahoo.com>
CC: xmlschema-dev@w3.org

Hi Shirish,

> I would like to have an element to have a type, which is a choices
> between number of types.

The only way the same element can take on different complex types in
XML Schema is if the types are related. You then have to switch
between the types using the xsi:type attribute on the element in the
instance document. For example:

a.xml =>
<Node xsi:type="Type1">
  <Sub1>
  <Sub2>
  <Sub3>
</Node>

b.xml =>
<Node xsi:type="Type2">
  <Sub4>
  <Sub5>
</Node>

Your types are related already, since they are both restrictions of
xs:anyType, so you could just use the declaration:

<xs:element name="Node" type="xs:anyType" />

but this would mean that the element could contain anything (unless
the xsi:type attributes were present). So it's probably best to create
an anonymous abstract type from which the two types can be derived by
extension:

<xs:complexType name="BaseType" abstract="true" />

<xs:complexType name="Type1">
  <xs:complexContent>
    <xs:extension base="BaseType">
      <xs:sequence>
        <xs:element name="Sub1" type="xsd:string"/>
        <xs:element name="Sub2" type="xsd:string"/>
        <xs:element name="Sub3" type="xsd:string"/>
      </xs:sequence>
    </xs:extension>
  </xs:complexContent>
</xs:complexType>

<xs:complexType name="Type2">
  <xs:complexContent>
    <xs:extension base="BaseType">
      <xs:sequence>
        <xs:element name="Sub4" type="xsd:string"/>
        <xs:element name="Sub5" type="xsd:string"/>
      </xs:sequence>
    </xs:extension>
  </xs:complexContent>
</xs:complexType>

You can then declare the element to be of that abstract base type:

<xs:element name="Node" type="BaseType" />

Cheers,

Jeni

---
Jeni Tennison
http://www.jenitennison.com/
Received on Tuesday, 4 March 2003 05:55:45 GMT

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