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

Re: conditional element content?

From: Eddie Robertsson <erobertsson@allette.com.au>
Date: Fri, 01 Nov 2002 10:02:32 +1100
Message-ID: <3DC1B688.9060607@allette.com.au>
To: Vaios Papanagnou <v.papanagnou@ucl.ac.uk>
Cc: xmlschema-dev <xmlschema-dev@w3.org>

Hi Vaios,

>Would it be possible to specify that an element's content can change
>conditionally, in relation with an attribute's value?
>
Normally this is a constraint that can't be done in W3C XML Schema. 
RELAX-NG has more support for this and Schematron is the leading schema 
language for these constraints. An alternative is to embedd Schematron 
rules in your W3C XML Schema [1].
However, in the particular case you have described there is one solution 
available in W3C XML Schema that you possibly can use. This does require 
that instead of using you're own type attribute you use the predefined 
xsi:type attribute where you specify the name of the type you want the 
element to use. Example follows:

>eg.
><element name="test" type="true">
><h1/>
></element>
>
><element name="test" type="false">
><h1/>
><h2/>
></element>
>
So, here you have two different types:

1) Only a "h1" element and a "name" attribute
2) Both "h1" and "h2" elements and a "name" attribute

<xs:complexType name="Type1">
   <xs:sequence>
      <xs:element name="h1" type="xs:string">
   </xs:sequence>
   <xs:attribute name="name" type="xs:string" use="required"/>
</xs:complexType>

<xs:complexType name="Type2">
   <xs:complexContent>
      <xs:extension base="Type1">
         <xs:sequence>
            <xs:element name="h2" type="xs:string">
         </xs:sequence>
      </xs:extension>
   </xs:complexContent>
</xs:complexType>

Now, you define the "element" element in the schema as having Type1

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

In the instance document you can now control which type the "element" 
element can have by specifying the xsi:type attribute:

<!-- You don't really need the xsi:type attribute on this since it 
should have Type1 but it's there for clarity -->
<element name="test" xsi:type="Type1">
   <h1/>
</element>

<element name="test" xsi:type="Type2">
   <h1/>
   <h2/>
</element>

This would be invalid:

<element name="test" xsi:type="Type2">
   <h1/>
</element>

You can read more about this at [2].

Cheers,
/Eddie

[1] http://www.topologi.com/public/Schtrn_XSD/Paper.html
[2] http://www.w3.org/TR/xmlschema-0/#UseDerivInInstDocs
Received on Thursday, 31 October 2002 18:04:30 GMT

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