XSD元素替换(Element Substitution)

XSD元素替换(Element Substitution)

作用:

通过 XML Schema,一个元素可对另一个元素进行替换

本章内容:

  • 全局元素

  • 元素替换

  • 阻止元素替换


全局元素

全局元素指 "schema" 元素的直接子元素!本地元素(Local elements)指嵌套在其他元素中的元素

元素替换

实例:

用户来自英国和挪威。我们希望有能力让用户选择在 XML 文档中使用挪威语的元素名称还是英语的元素名称

<xs:element name="name" type="xs:string"/>
<xs:element name="navn" substitutionGroup="name"/>
<!--"name" 元素是主元素,而 "navn" 元素可替代 "name" 元素-->
<!--
在 XML schema 中定义一个 substitutionGroup。
首先,我们声明主元素
然后我们会声明次元素
这些次元素可声明它们能够替换主元素。
-->

实例2:

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

<xs:complexType name="custinfo">
 <xs:sequence>
   <xs:element ref="name"/>
     <!--ref类似href,引用链接-->
 </xs:sequence>
</xs:complexType>

<xs:element name="customer" type="custinfo"/>
<xs:element name="kunde" substitutionGroup="customer"/>

根据上面的schema,有效的XML文档类似这样:

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

or

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

阻止元素替换

使用属性:block

实例:

<xs:element name="name" type="xs:string" block="substitution"/>
<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"/>

根据上面的schema,有效的XML文档类似这样:

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

不合法:

<kunde>
 <navn>John Smith</navn>
</kunde>
<!--因为用了block属性,所以这个xml文档不合法-->
注意:

substitutionGroup 中的所有元素(主元素和可替换元素)必须被声明为全局元素,否则就无法工作!

It's a lonely road!!!
原文地址:https://www.cnblogs.com/JunkingBoy/p/14656484.html