XSD:仅限制一个子元素具有特定值 [英] XSD: Restrict only one child element to have specific value
本文介绍了XSD:仅限制一个子元素具有特定值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个 XML 读取
I have a XML which reads
<Options>
<option1>Y</option1>
<option2>N</option2>
<option3>N</option3>
</Options>
我想确保只有一个子元素(选项)具有值 Y,这样上面的 XML 是有效的,但下面的无效.
I would like to ensure only one child element (of Options) has value Y so that above XML is valid but not the below one.
<Options>
<option1>Y</option1>
<option2>Y</option2>
<option3>N</option3>
</Options>
我尝试了独特的参照完整性,但没有成功.
I tried unique and referential integrity but couldn't work out.
非常感谢任何帮助/想法.
Any help/idea much appreciated.
推荐答案
您必须在 XSD 1.0 之外强制实施这样的约束,但您可以使用 xs:assert
来强制实施它 <强>XSD 1.1:
You'd have to enforce such a constraint outside of XSD 1.0, but you could use xs:assert
to enforce it with XSD 1.1:
<?xml version="1.0" encoding="UTF-8"?>
<xs:schema attributeFormDefault="unqualified"
elementFormDefault="qualified"
xmlns:xs="http://www.w3.org/2001/XMLSchema"
xmlns:vc="http://www.w3.org/2007/XMLSchema-versioning"
vc:minVersion="1.1">
<xs:element name="Options">
<xs:complexType>
<xs:sequence>
<xs:element name="option1"/>
<xs:element name="option2"/>
<xs:element name="option3"/>
</xs:sequence>
<xs:assert test="count(* = 'Y') = 1"/>
</xs:complexType>
</xs:element>
</xs:schema>
或者,避免单独命名每个option
:
<?xml version="1.0" encoding="UTF-8"?>
<xs:schema attributeFormDefault="unqualified"
elementFormDefault="qualified"
xmlns:xs="http://www.w3.org/2001/XMLSchema"
xmlns:vc="http://www.w3.org/2007/XMLSchema-versioning"
vc:minVersion="1.1">
<xs:element name="Options">
<xs:complexType>
<xs:sequence>
<xs:element name="option" maxOccurs="unbounded" />
</xs:sequence>
<xs:assert test="count(option = 'Y') = 1"/>
</xs:complexType>
</xs:element>
</xs:schema>
如果需要,当然也可以将选项限制为只有 Y
或 N
.
Constraining options to be only Y
or N
could of course also been done if desired.
这篇关于XSD:仅限制一个子元素具有特定值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文