XSD Element Substitution (Element Substitution)

Through XML Schema, one element can replace another element.

Element Replacement

Let's take an example: our users come from the United Kingdom 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 substitutionGroupFirst, we declare the main element, and then we declare the secondary elements, which can declare that they can replace 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.

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 similar:

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

Prevent 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>

Use substitutionGroup

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

Please note that all elements (main elements and substitutable elements) within 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.