Latest web development tutorials

Replace XML Schema elements

By XML Schema, an element can be replaced with another element.


Replaced elements

Let us illustrate: our customers from the UK and Norway. We want to have the ability to let users choose to use the Norwegian element names in the XML document or the English name of the element.

To solve this problem, we can define a substitutionGroup in the XML schema. First, we declare the main element, then we will declare minor elements, these elements can be declared once they are able to replace the primary element.

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

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

Consider a XML schema fragment:

<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"/>

Valid XML document like this (according to the above schema):

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

Or something like this:

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


Replace stop element

To prevent other elements replace a specified element, use the block properties:

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

See an XML schema fragment:

<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"/>

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

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

However, the following document is no longer legitimate:

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


Use substitutionGroup

Replaceable elements must be the main elements of the same type, or derived from the main element. If the type can replace elements of the main elements of the same type, you will not have to specify the type of the element can be replaced.

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


What is the global element (Global Elements)?

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