要允许属性取决于其他属性的内容,您需要XSD 1.1(或某些XSD 1.0扩展,如Schematron)。在XSD 1.1中,您可以使用断言xs:assert
,在此声明使用XPath为复杂类型声明规则。
为了验证这一实例:
<modes>
<A mode="ENABLE" attr1="abc" attr2="xyz" />
<A mode="DISABLE" attr3="abc" attr4="xyz" />
</modes>
可以使用XSD类似下面:
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" elementFormDefault="qualified"
xmlns:vc="http://www.w3.org/2007/XMLSchema-versioning" vc:minVersion="1.1">
<xs:element name="modes">
<xs:complexType>
<xs:sequence>
<xs:element ref="A" minOccurs="0" maxOccurs="unbounded"/>
</xs:sequence>
</xs:complexType>
</xs:element>
<xs:attributeGroup name="enabled-attributes">
<xs:attribute name="attr1" type="xs:string" use="optional"/>
<xs:attribute name="attr2" type="xs:string" use="optional"/>
</xs:attributeGroup>
<xs:attributeGroup name="disabled-attributes">
<xs:attribute name="attr3" type="xs:string" use="optional"/>
<xs:attribute name="attr4" type="xs:string" use="optional"/>
</xs:attributeGroup>
<xs:element name="A">
<xs:complexType>
<xs:attributeGroup ref="disabled-attributes"/>
<xs:attributeGroup ref="enabled-attributes"/>
<xs:attribute name="mode" use="required">
<xs:simpleType>
<xs:restriction base="xs:NMTOKEN">
<xs:enumeration value="ENABLE" />
<xs:enumeration value="DISABLE" />
</xs:restriction>
</xs:simpleType>
</xs:attribute>
<xs:assert test="(@mode='ENABLE' and @attr1 and @attr2 and not(@attr3) and not(@attr4))
or (@mode='DISABLE' and @attr3 and @attr4 and not(@attr1) and not(@attr2))"/>
</xs:complexType>
</xs:element>
</xs:schema>
我放置在属性为每个模式单独的属性组中使用。您的mode
属性实际上并不是fixed
,但可以有两个值,因此我使用枚举将它限制为这两个值。
需要XSD 1.1的行是xs:assert
行。 XPath表达式是相对于复杂类型中的元素计算的。如果表达式是真的,它将被验证。
否则验证将失败。这些A
节点都将无法通过验证:
<modes>
<A mode="DISABLE" attr1="fgs" attr4="hjs" />
<A mode="ENABLE" attr3="fgs" attr4="hjs" />
</modes>
更新:我添加上述not()
条款,因为该声明是不完整的,你说。现在,这验证为假:
<A mode="DISABLE" attr1="fgs" attr2="hjs" attr3="fgs" attr4="fgs"/>
您也可以使用其他的标准(这是一个XPath的子集),如属性的数量,例如,如果你有很多的属性,并希望避免很多not()
条款可以使用:
@mode='ENABLE' and @attr1 and @attr2 and count(@*) = 3
,将属性的总数限制为3。
这也通过模式验证:''所以它似乎是部分正确的,谢谢你的支持,你可以请求e再次增强了这个答案。 –
没错。我会编辑答案。 – helderdarocha