XSD Element Substitution (Element Substitution)

Through XML Schema, one element can replace another element.

Element Replacement

Let's illustrate with an example: our users come from the UK and Norway. We want to be able to allow users to choose whether to use Norwegian or English element names in the XML document.

To solve this problem, we can define a substitutionGroup.Firstly, we declare the primary element, and then we declare secondary elements that can declare their ability to replace the primary element.

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

In the above example, the "name" element is the primary element, while the "navn" element can replace the "name" element.

See 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 should look something like this (based on the above schema):

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

Or something like this:

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

Preventing Element Replacement

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

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

See 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 something like this (based on the above schema):

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

However, 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 the primary element, or derived from the primary element. If the type of the substitutable element is the same as the type of the primary element, then you do not need to specify the type of the substitutable element.

Please note that all elements (primary elements and substitutable elements) in the substitutionGroup must be declared as global elements, otherwise they will not work!

What Are Global Elements (Global Elements)?

Global elements refer to the direct children of the "schema" element! Local elements (Local elements) refer to elements nested within other elements.