XSD Element Substitution
With XML Schemas, one element can substitute another element.
Element Substitution
Element substitution consists of defining an element that can be replaced by another element.
Element substitution can be done with:
substitutionGroup
attributeblock
attribute
Substitution with substitutionGroup attribute
The type of the substitutable must be the same as or derived from the type of the leading element. If the type of the substitutable element is the same as the type of the header element, you will not have to specify the type of the replaceable element.
All elements in the substitutionGroup
(the head element and the substitutable elements) must be declared as global elements, otherwise it will not work!
Global elements are elements that are immediate children of the "schema" element!
Local elements are elements nested within other elements.
We first declare a main element and then we declare the other elements that are replaceable to the main element:
In this example, the name
element is the head element and the navn
element is substitutable for name
.
<xs:element name="name" type="xs:string"/>
<xs:element name="navn" substitutionGroup="name"/>
Look this 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="client" substitutionGroup="customer"/>
A valid XML document (according to the schema above) looks like this:
<customer>
<name>Tom Nolan</name>
</customer>
or like this:
<client>
<name>Tom Nolan</name>
</client>
Substitution with block attribute
To prevent other elements from substituting with a specified element, use the block
attribute:
<xs:element name="name" type="xs:string" block="substitution"/>
For example:
<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="client" substitutionGroup="customer"/>
A valid XML document (according to the schema above) looks like this:
<customer>
<name>Tom Nolan</name>
</customer>
but this is no longer valid:
<client>
<name>Tom Nolan</name>
</client>