XSD Element Substitution


Through XML Schema, one element can substitute another element.


Element Substitution

Let's illustrate: Our users come from the UK and Norway. We want to give users the ability to choose whether to use Norwegian element names or English element names in XML documents.

To solve this problem, we can define asubstitutionGroup. First, we declare the main element, then we declare secondary elements, which can declare that they can substitute the main element.

<xs:element name="name" type="xs:string"/>
<xs:element name="navn" substitutionGroup="name"/>

In the above example, the "name" element is the main element, and the "navn" element can replace the "name" element.

Here is a fragment of an XML schema:

<xs:element name="name" type="xs:string"/>
<xs:element name="navn" substitutionGroup="name"/>

<xs:complexType name="custinfo">
  <xs:sequence>
    <xs:element ref="name"/>
  </xs:sequence>
</xs:complexType>

<xs:element name="customer" type="custinfo"/>
<xs:element name="kunde" substitutionGroup="customer"/>

A valid XML document would look like this (according to the above schema):

<customer>
  <name>John Smith</name>
</customer>

Or like this:

<kunde>
  <navn>John Smith</navn>
</kunde>


Blocking Element Substitution

To prevent other elements from substituting a specified element, use the block attribute:

<xs:element name="name" type="xs:string" block="substitution"/>

Here is a fragment of an XML schema:

<xs:element name="name" type="xs:string" block="substitution"/>
<xs:element name="navn" substitutionGroup="name"/>

<xs:complexType name="custinfo">
  <xs:sequence>
    <xs:element ref="name"/>
  </xs:sequence>
</xs:complexType>

<xs:element name="customer" type="custinfo" block="substitution"/>
<xs:element name="kunde" substitutionGroup="customer"/>

A valid XML document should look like this (according to the above schema):

<customer>
  <name>John Smith</name>
</customer>

But the following document is no longer valid:

<kunde>
  <navn>John Smith</navn>
</kunde>


Using substitutionGroup

The type of the substitutable element must be the same as that of the main element, or derived from the main element. If the type of the substitutable element is the same as the main element's type, then you do not need to specify the type of the substitutable element.

Note that all elements (the main element and substitutable elements) in the substitutionGroup must be declared as global elements, otherwise it will not work!


What are Global Elements?

Global elements are direct children of the "schema" element! Local elements are elements nested within other elements.

Other Extensions