XSD Element Substitution

For one element to substitute another element, we can use the XML Schemas.

Element Substitution:

We can have users from different countries, let’s say, the USA and Italy. Now, to let the user choose either to use the Italian element names or the English element names in the XML document, we could define a substitutionGroup in the XML schema. For this, we will first declare a head element. The other elements will be then declared to state that they are substitutable for the head element.

Example:

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

Explanation:

In the above example, the head element is the “name” element and the substitutable for “name” is the “nome” element.

XML schema:

<xs:element name="name" type="xs:string"></xs:element>
<xs:element name="nome" substitutionGroup="name"></xs:element>
 
<xs:complextype name="custinfo">
  <xs:sequence>
    <xs:element ref="name"></xs:element>
  </xs:sequence>
</xs:complextype>
 
<xs:element name="customer" type="custinfo"></xs:element>
<xs:element name="cliente" substitutionGroup="customer"></xs:element>

Valid XML document:

<customer>
  <name>Tony Jonas</name>
</customer>

OR

<cliente>
  <nome>Tony Jonas</nome>
</cliente>

Blocking Element Substitution:

The block attribute can be used to prevent other elements from substituting with a specified element.

Example:

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

XML schema:

<xs:element name="name" type="xs:string" block="substitution"></xs:element>
 
<xs:element name="nome" substitutionGroup="name"></xs:element>
 
<xs:complextype name="custinfo">
  <xs:sequence>
    <xs:element ref="name"></xs:element>
  </xs:sequence>
</xs:complextype>
 
<xs:element name="customer" type="custinfo" block="substitution"></xs:element>
<xs:element name="cliente" substitutionGroup="customer"></xs:element>

Valid XML document:

<customer>
  <name>Tony Jonas</name>
</customer>

NO LONGER VALID:

<cliente>
  <nome>Tony Jonas</nome>
</cliente>

Using substitutionGroup:

It is not required to specify the type of the substitutable element when the type of the substitutable element is the same as the type of the head element, thus, the type of the substitutable elements must be the same as, or derived from, the type of the head element. Also, the head element and the substitutable elements, i.e., all elements in the substitutionGroup, must be declared as global elements for them to work.

What are Global Elements?

The elements that are the immediate children of the “schema” element are called the Global elements, while the elements nested within other elements are called the Local elements.

Please Share