如何在XSD 1.0中限制XML元素的两个属性不同时存在?
在XSD 1.0中限制
<bottle>元素不同时存在volume和size属性的实现方案 XSD 1.0本身没有直接提供属性互斥的约束语法,要实现“仅单独使用volume、单独使用size,或不使用任何属性”的要求,需要通过属性组(attributeGroup)结合<choice>元素来实现核心逻辑。以下是具体的XSD实现代码:
<?xml version="1.0" encoding="UTF-8"?> <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"> <!-- 定义包含volume属性的属性组 --> <xs:attributeGroup name="volumeAttrGroup"> <xs:attribute name="volume" type="xs:int" use="required"/> </xs:attributeGroup> <!-- 定义包含size属性的属性组 --> <xs:attributeGroup name="sizeAttrGroup"> <xs:attribute name="size" type="xs:string" use="required"/> </xs:attributeGroup> <!-- container元素定义 --> <xs:element name="container"> <xs:complexType> <xs:sequence> <xs:element name="bottle"> <xs:complexType> <!-- 使用choice实现属性组的互斥选择,minOccurs="0"允许不选任何属性组 --> <xs:choice minOccurs="0"> <xs:attributeGroup ref="volumeAttrGroup"/> <xs:attributeGroup ref="sizeAttrGroup"/> </xs:choice> </xs:complexType> </xs:element> </xs:sequence> </xs:complexType> </xs:element> </xs:schema>
逻辑说明:
- 将
volume和size分别封装到独立的属性组中,每个属性组内的属性设置为use="required",确保选择该属性组时必须包含对应的属性。 - 在
<bottle>的复杂类型定义中,使用<choice>元素包裹两个属性组,并设置minOccurs="0",这意味着:- 可以选择
volumeAttrGroup(仅包含volume属性); - 可以选择
sizeAttrGroup(仅包含size属性); - 可以不选择任何属性组(即
<bottle>无属性); - 无法同时选择两个属性组,自然也就禁止了
volume和size同时出现的情况。
- 可以选择
验证示例:
允许的XML实例:
示例1(仅含volume属性):
<container> <bottle volume="1"/> </container>
示例2(仅含size属性):
<container> <bottle size="small"/> </container>
示例3(无属性):
<container> <bottle/> </container>
禁止的XML实例:
<container> <bottle volume="1" size="small"/> </container>
该实例会被XSD验证拒绝,因为它同时包含了两个属性组的属性,违反了<choice>的互斥规则。
内容的提问来源于stack exchange,提问作者Autechre
相关产品推荐
相关产品推荐

