如何用XSD的type alternatives限制仅text/select类型field可含field-option?
按字段类型控制field-option的存在性
需求说明
现有XSD用于定义field元素,类型限定为text|select|password|checkbox,当前允许所有类型的field可选包含field-option列表。需要修改为:仅text和select类型的field可包含field-option,password和checkbox类型的field必须没有子元素。
示例合法XML
<fields> <field type="text" /> <field type="select"> <field-option>Option 1</field-option> <field-option>Option 2</field-option> <field-option>Option 3</field-option> </field> <field type="password" /> <field type="checkbox" /> </fields>
修改后的XSD代码
要实现这个逻辑,需要使用XSD 1.1的xs:alternative特性(XSD 1.0不支持该特性,需声明版本)。具体代码如下:
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" version="1.1"> <!-- 定义允许包含field-option的字段类型 --> <xs:complexType name="FieldWithOptionsType"> <xs:sequence> <xs:element name="field-option" type="xs:string" minOccurs="0" maxOccurs="unbounded" /> </xs:sequence> <xs:attribute name="type" use="required"> <xs:simpleType> <xs:restriction base="xs:string"> <xs:pattern value="text|select" /> </xs:restriction> </xs:simpleType> </xs:attribute> </xs:complexType> <!-- 定义不允许包含子元素的字段类型 --> <xs:complexType name="FieldWithoutOptionsType"> <xs:sequence /> <xs:attribute name="type" use="required"> <xs:simpleType> <xs:restriction base="xs:string"> <xs:pattern value="password|checkbox" /> </xs:restriction> </xs:simpleType> </xs:attribute> </xs:complexType> <xs:element name="fields" minOccurs="0"> <xs:complexType> <xs:sequence> <xs:element name="field" maxOccurs="unbounded"> <!-- 根据type属性选择对应的complexType --> <xs:alternative test="@type = 'text' or @type = 'select'" type="FieldWithOptionsType" /> <xs:alternative test="@type = 'password' or @type = 'checkbox'" type="FieldWithoutOptionsType" /> </xs:element> </xs:sequence> </xs:complexType> </xs:element> </xs:schema>
关键逻辑说明
- 版本声明:根元素
xs:schema必须加上version="1.1",否则xs:alternative无法生效。 - 拆分类型:
FieldWithOptionsType:包含field-option子元素,且type属性只能是text或select。FieldWithoutOptionsType:没有任何子元素(空的xs:sequence),且type属性只能是password或checkbox。
- 类型选择:在
field元素内通过xs:alternative,根据type属性的值匹配对应的complexType,实现不同类型字段的子元素限制。
验证规则
text/select类型的field:可以包含0到多个field-option,也可以为空。password/checkbox类型的field:如果添加field-option子元素,XML验证会直接失败。
内容的提问来源于stack exchange,提问作者striderhobbit
相关产品推荐
相关产品推荐

