如何在 XML 模式中指定必须存在两个字段之一? [英] How to specify in an XML schema that either one of two fields must be present?
问题描述
我想指定 fieldname
或 freetext
必须始终出现在适用于此 XSD 的 XML 文件中.有没有办法做到这一点?
I want to specify that either fieldname
or freetext
must always be present in XML files that apply to this XSD. Is there a way to do that?
<xs:complexType name="tSome">
<xs:sequence>
<!-- either one of the two below has to be present. -->
<xs:element name="fieldname" type="xs:string" />
<xs:element name="freetext" type="xs:string" />
<!-- this one below must always be present -->
<xs:element name="dbtablename" type="xs:string" />
</xs:sequence>
</xs:complexType>
推荐答案
有一个Choice Indicator 在 XML Schema 中,它允许您使用一个包含的元素,但不能使用两个或更多.如果您想要 3 个中的任何 2 个,我建议您执行以下操作:
There is a Choice Indicator in XML Schema, which allows you to take one of the contained elements, but not two or more. If you want any 2 of 3, I suggest doing something like this:
<xs:choice>
<xs:element name="fieldname" type="xs:string" minOccurs="0" maxOccurs="1" />
<xs:element name="freetext" type="xs:string" minOccurs="0" maxOccurs="1" />
<xs:element name="dbtablename" type="xs:string" minOccurs="0" maxOccurs="1" />
</xs:choice>
<xs:choice>
<xs:element name="fieldname" type="xs:string" minOccurs="0" maxOccurs="1" />
<xs:element name="freetext" type="xs:string" minOccurs="0" maxOccurs="1" />
<xs:element name="dbtablename" type="xs:string" minOccurs="0" maxOccurs="1" />
</xs:choice>
(也许 maxOccurs
会阻止您选择同一个元素两次.)如果那行不通,我什么都不会想.
(Maybe maxOccurs
will prevent you from choosing one and the same element twice.)
If that does not work, nothing will I think.
编辑:我第一次没有正确理解问题.如果您希望 dbtablename
始终与 fieldname
或 freetext
中的任何一个一起出现,那么这就是答案:
Edited: I didn't correctly understand the question the first time. If you want dbtablename
to always be present with any one of fieldname
or freetext
, then this is the answer:
<xs:complexType name="tSome">
<xs:sequence>
<xs:choice>
<xs:element name="fieldname" type="xs:string" />
<xs:element name="freetext" type="xs:string" />
</xs:choice>
<xs:element name="dbtablename" type="xs:string" />
</xs:sequence>
</xs:complexType>
这篇关于如何在 XML 模式中指定必须存在两个字段之一?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!