XML Schema Tuto...login
XML Schema Tutorial
author:php.cn  update time:2022-04-20 14:13:02

XML Schema element replacement


XSD Element Substitution


Through XML Schema, one element can replace another element.


Element Replacement

Let’s give an example: our users are from the UK and Norway. We would like to have the ability for users to choose whether to use Norwegian or English element names in an XML document.

To solve this problem, we can define a substitutionGroup in the XML schema. First, we declare the main element, and then we declare the secondary elements, which 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.

Please look at a fragment of 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 looks like this (according to the above schema):

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

or similar:

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


##Prevent element replacement

To prevent other elements from replacing an element For the specified element, please use the block attribute:

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

Please look at 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"/>

The legal XML document should be similar to this (according to the above schema):

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

But 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 Identical, or derived from the primary 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 in the substitutionGroup (main elements and replaceable elements) must be declared as global elements, otherwise it will not work!


What are Global Elements?

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