Zastąpienie elementów (Element Substitution) XSD
- Poprzednia strona XSD <anyAttribute>
- Następna strona Przykład XSD
Przez XML Schema, jeden element może zastąpić inny element.
Zastępowanie 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ą używać nazw elementów w języku norweskim czy angielskim.
Aby rozwiązać ten problem, możemy zdefiniować jedną z nich w XML schema. substitutionGroupNajpierw deklarujemy główny element, a następnie deklarujemy elementy pomocnicze, które mogą zastąpić główny element.
<xs:element name="name" type="xs:string"/> <xs:element name="navn"}} substitutionGroup="name"/>
W powyższym przykładzie, element "name" jest elementem głównym, a 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 podobnie:
<kunde> <navn>John Smith</navn> </kunde>
Zapobieganie zastępowaniu elementów
Aby zapobiec zastępowaniu innego elementu 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 poniższy dokument nie jest już legalny:
<kunde> <navn>John Smith</navn> </kunde>
Użyj substitutionGroup
Typ elementu zastępczego musi być taki sam jak typ głównego elementu, lub pochodzić z głównego elementu. Jeśli typ elementu zastępczego jest taki sam jak typ głównego elementu, 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 oznaczają bezpośrednie podelementy "schema"! Lokalne elementy (Local elements) to elementy umieszczone wewnątrz innych elementów.
- Poprzednia strona XSD <anyAttribute>
- Następna strona Przykład XSD