Zastąpienie elementów XSD (Element Substitution)

Dzięki XML Schema, jeden element może zastąpić inny.

Zastąpienie elementów

Pozwólmy sobie na przykład: nasi użytkownicy pochodzą z Wielkiej Brytanii i Norwegii. Chcemy mieć możliwość wyboru, czy w dokumencie XML użytkownicy będą mogli wybrać nazwy elementów w języku norweskim czy angielskim.

Aby rozwiązać ten problem, możemy zdefiniować w schemacie XML: substitutionGroupNa początku deklarujemy główny element, a następnie deklarujemy elementy pomocnicze, które mogą deklarować, że mogą zastępować główny element.

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

W powyższym przykładzie, element "name" jest głównym elementem, podczas gdy element "navn" może zastępować element "name".

Zobacz fragment jakiegoś schematu XML:

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

Prawidłowy dokument XML powinien wyglądać mniej więcej tak (na podstawie powyższego schematu):

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

lub coś w tym stylu:

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

Zapobieganie zastępowaniu elementów

Aby zapobiec zastępowaniu innych elementów przez określony element, użyj atrybutu block:

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

Zobacz fragment jakiegoś schematu XML:

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

Prawidłowy dokument XML powinien wyglądać mniej więcej tak (na podstawie powyższego schematu):

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

Ale dokument poniżej już nie jest ważny:

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

Użycie substitutionGroup

Typy elementów zastępczych muszą być takie same jak typy elementów głównych lub pochodne od nich. Jeśli typ elementu zastępczego jest taki sam jak typ elementu głównego, nie musisz określać typu elementu zastępczego.

Proszę zauważyć, że wszystkie elementy w substitutionGroup (elementy główne i elementy zastępcze) muszą być zadeklarowane jako globalne elementy, w przeciwnym razie nie będą działać!

Co to są globalne elementy (Global Elements)?

Globalne elementy to bezpośrednie podelementy elementu "schema"! Lokalne elementy (Local elements) to elementy wstawione w inne elementy.