如何在XML Schema定义中选择一个且仅一个元素

时间:2011-03-19 15:27:00

标签: xml xsd

如果之前已经询问过,但是我已经搜索了网站,那么道歉......

无论如何,我一直在努力研究如何在XML Schema中强制选择一个且只有一个元素。

例如,假设您只需要选择一种苹果,橙子或香蕉元素,但您不能没有苹果,橙子或香蕉元素。

现在我尝试过这个:

<?xml version="1.0" encoding="utf-8" ?>
<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema"
            targetNamespace="http://tempuri.org/Fruit"
            xmlns="http://tempuri.org/Fruit"
            elementFormDefault="qualified">

      <xsd:complexType mixed="true">
        <xsd:sequence>
            <xsd:choice minOccurs="0" maxOccurs="1">
              <xsd:element name="banana" type="xsd:string"/>
              <xsd:element name="apple" type="xsd:string"/>
              <xsd:element name="orange" type="xsd:string"/>
            </xsd:choice>
        </xsd:sequence>
      </xsd:complexType mixed="true">

</xsd:schema>

现在这很棒,但是<choice>不是一个而只有一个,但实际上零或只有一个。如何将基数强制为XML Schema Definition文件中的唯一一个?

2 个答案:

答案 0 :(得分:2)

这样:

<xsd:choice minOccurs="1" maxOccurs="1">

修改架构:我添加了Fruit - root并将xsd更改为xs

<?xml version="1.0"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"
targetNamespace="http://www.w3schools.com"
xmlns="http://www.w3schools.com"
elementFormDefault="qualified">

<xs:element name="Fruit">
      <xs:complexType  mixed="true">
        <xs:sequence>
            <xs:choice minOccurs="1" maxOccurs="1">
              <xs:element name="banana" type="xs:string"/>
              <xs:element name="apple" type="xs:string"/>
              <xs:element name="orange" type="xs:string"/>
            </xs:choice>
        </xs:sequence>
      </xs:complexType>
</xs:element>
</xs:schema>

答案 1 :(得分:0)

@smas的回答是正确的。但是,如果未在xs:choice(source)中明确声明,则minOccurs和maxOccurs属性均默认为1。这样您就可以摆脱xs:choice的属性,并获得所需的行为。

相关问题