【发布时间】:2010-10-20 06:27:55
【问题描述】:
有没有办法指定 XSD 中需要 2 个属性之一?
例如,我有一个这样的定义:
<xs:attribute name="Name" type="xs:string" use="optional" />
<xs:attribute name="Id" type="xs:string" use="optional" />
我希望能够定义至少其中一项是必需的。这可能吗?
【问题讨论】:
标签: xsd
有没有办法指定 XSD 中需要 2 个属性之一?
例如,我有一个这样的定义:
<xs:attribute name="Name" type="xs:string" use="optional" />
<xs:attribute name="Id" type="xs:string" use="optional" />
我希望能够定义至少其中一项是必需的。这可能吗?
【问题讨论】:
标签: xsd
不,我不认为你可以用属性来做到这一点。您可以将两个 <xs:element> 包装成一个 <xs:choice> - 但对于属性,恐怕没有等效的构造。
【讨论】:
XSD 1.1 将允许您使用断言来执行此操作。
<xsd:element name="remove">
<xsd:complexType>
<xsd:attribute name="ref" use="optional"/>
<xsd:attribute name="uri" use="optional"/>
<xsd:assert test="(@ref and not(@uri)) or (not(@ref) and @uri)"/>
</xsd:complexType>
</xsd:element>
【讨论】:
<xsd:assert test="(@ref or @uri)"/> 的事情吗?
Marc 说的很对……你不能在 XSD 中的 xs:choice 父元素中包含 xs:attribute 子元素。
逻辑似乎是,如果一个元素的两个实例具有一组互斥的属性,那么它们在逻辑上是两个不同的元素。
Jeni Tennison here 提出了解决此问题的方法。
【讨论】:
您应该查看 W3C wiki 上的以下页面:Simple attribute implication 和 Attribute muttex
【讨论】:
该示例定义了一个名为“person”的元素,该元素必须包含“employee”元素或“member”元素。
<xs:element name="person">
<xs:complexType>
<xs:choice>
<xs:element name="employee" type="employee"/>
<xs:element name="member" type="member"/>
</xs:choice>
</xs:complexType>
</xs:element>
【讨论】: