【问题标题】:Most Efficient Schema For This OR That, or This AND ThatThis OR That 或 This AND That 的最有效模式
【发布时间】:2010-01-19 20:08:02
【问题描述】:

我正在尝试编写一个允许 XML 以下列方式表达的 XML 模式:

宠物可以同时包含猫和狗元素:

<root>
  <pets>
    <cat />
    <dog />
  </pets>
</root>

宠物可以只包含猫或狗元素

<root>
  <pets>
    <cat />
  </pets>
</root>
-----------
<root>
  <pets>
    <dog />
  </pets>
</root>

如果 pets 没有子元素,那么它应该是不存在的:

<root>
</root>

我想出的满足这些条件的最佳架构是这样的:

<xs:element name="pets">
  <xs:complexType>
    <xs:choice>
      <xs:sequence>
        <xs:element name="cat"/>
        <xs:element name="dog" minOccurs="0"/>
      </xs:sequence>
      <xs:sequence>
        <xs:element name="dog"/>
      </xs:sequence>
    </xs:choice>
  </xs:complexType>
</xs:element>

在我看来,对于这样一个简单的概念来说,这似乎太多了。有没有更简单的方法来编写这个模式?谢谢!

【问题讨论】:

    标签: xml schema xsd


    【解决方案1】:

    我认为这是使用 xs:group 元素的理想情况:如果您将其包裹在您的元素周围并使其成为可选(同时使元素的内容成为强制性),您将获得所需的效果。

    <xs:group name="pets_group">
      <xs:element name="pets" minOccurs="0" maxOccurs="1">
        <xs:complexType>
          <xs:choice>
            <xs:sequence>
              <xs:element name="cat"/>
              <xs:element name="dog" minOccurs="0"/>
            </xs:sequence>
            <xs:sequence>
              <xs:element name="dog"/>
              <xs:element name="cat" minOccurs="0"/>
            </xs:sequence>
          </xs:choice>
        </xs:complexType>
      </xs:element>
    </xs:group>
    

    那么不要使用pets元素,而是使用pets_group组:

    <xs:element name="root">
      <xs:complexType>
        <xs:group ref="pets_group"/>
      </xs:complexType>
    </xs:element>
    

    在猫后接可选狗和狗后接可选猫之间进行选择可确保宠物标签中包含 something。 pets 标签的缺失允许您不指定任何宠物。

    或者,您可以将它们一起定义,只需“内联”组引用即可。如果pets标签只用在一个地方,这可能是你想要做的。

    【讨论】:

      【解决方案2】:

      您在问题中提供的解决方案是最常见的解决方案。除了另一个答案中的团体想法之外,没有更好的方法。就个人而言,我更喜欢您的解决方案。

      大标准架构(例如FpML)使用您的模式。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-09-25
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-10-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多