Re: conditional element content?

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 UTC