ZVON > Tutorials > XML Schema and Relax NG Tutorial
Index | >> Example 2 / 2 << | Prev | Next |
Contents > Extensions of complexTypes > Extension of a choice

Extension of a choice

  1. XML Schema
  2. Relax NG

Please, send all comments, bug-reports, and contributions to Jiri.Jirat@systinet.com. Thank you very much.

XML Schema keys: choice, extension
Relax NG keys: choice, define, ref

1. XML Schema

When we extend a complexType, which contains a "choice", with another "choice", then the result will be a sequence of the choices.

Valid document


<root xsi:noNamespaceSchemaLocation="correct_0.xsd" xmlns="" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" >
  <x>1</x>
  <z>1</z>
</root>

Valid document


<root xsi:noNamespaceSchemaLocation="correct_0.xsd" xmlns="" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" >
  <y>1</y>
  <z>1</z>
</root>

Invalid document
The element "z" is missing.


<root xsi:noNamespaceSchemaLocation="correct_0.xsd" xmlns="" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" >
  <x>3</x>
</root>

Correct XML Schema (correct_0.xsd)


<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema" >

  <xsd:element name="root" type="BBB"/>

  <xsd:complexType name="AAA">
    <xsd:choice>
      <xsd:element name="x" type="xsd:string" minOccurs="1" maxOccurs="1"/>
      <xsd:element name="y" type="xsd:string" minOccurs="1" maxOccurs="1"/>
    </xsd:choice>
  </xsd:complexType>

  <xsd:complexType name="BBB">
    <xsd:complexContent>
      <xsd:extension base="AAA">
        <xsd:choice>
          <xsd:element name="z" type="xsd:string" minOccurs="1" maxOccurs="1"/>
        </xsd:choice>
      </xsd:extension>
    </xsd:complexContent>
  </xsd:complexType>
</xsd:schema>

2. Relax NG

We can simulate the same behaviour in Relax NG using the "define" and "ref" elements.

Valid document


<root xmlns="">
  <x>1</x>
  <z>1</z>
</root>

Valid document


<root xmlns="">
  <y>1</y>
  <z>1</z>
</root>

Invalid document
The element "z" is missing.


<root xmlns="">
  <x>3</x>
</root>

Correct Relax NG schema (correctRelax_0.rng)


<grammar ns="" xmlns="http://relaxng.org/ns/structure/1.0" >

  <start>
    <element name="root">
      <ref name="BBB"/>
    </element>
  </start>

  <define name="AAA">
    <choice>
      <element name="x">
        <text/>
      </element>
      <element name="y">
        <text/>
      </element>
    </choice>
  </define>

  <define name="BBB">
    <ref name="AAA"/>
    <element name="z">
      <text/>
    </element>
  </define>
</grammar>