多个 XML 元素的 XSD 架构,其中至少有一个元素,以任何顺序 [英] XSD schema for multiple XML elements with at least one present, in any order

查看:23
本文介绍了多个 XML 元素的 XSD 架构,其中至少有一个元素,以任何顺序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的 XML:

<animals>
  <cat/>
  <dog/>
  <cat/>
  <cat/>
</animals>

元素可以按任意顺序排列,并且可以有任意数量的元素.但我确实需要确保至少有一个 和至少一个 存在.我无法理解我的 XSD 应该是什么样子.

<cat/> and <dog/> elements can go in any order and there can be any number of them. But I do need to be sure that at least one <cat/> and at least one <dog/> is there. I can't understand how my XSD must look like.

这是我试过的:

<xs:complexType name="animals">
  <xs:choice minOccurs="1" maxOccurs="unbounded">
    <xs:element name="cat" minOccurs="1" maxOccurs="unbounded"/>
    <xs:element name="dog" minOccurs="1" maxOccurs="unbounded"/>
  </xs:choice>
</xs:complexType>

例如,当没有 时,它不会显示任何错误.

It doesn't show any errors when there are no <cat/>, for example.

推荐答案

使用 XSD 1.1,应该很简单:

With XSD 1.1, it should be as simple as:

<xs:complexType name="animals">
  <xs:all>
    <xs:element name="cat" minOccurs="1" maxOccurs="unbounded"/>
    <xs:element name="dog" minOccurs="1" maxOccurs="unbounded"/>
  </xs:all>
</xs:complexType>

对于 XSD 1.0,它变得有点棘手.但是,我们可以观察到任何有效的 的序列必须以 元素开头.第一个元素可能会重复,但有一次,必须有另一个元素的第一个实例.所以这给出了两种可能的序列的选择.在我们确保至少有一个 和一个 元素之后,可以有任意数量的附加元素:

With XSD 1.0, it gets a bit tricky. However, we can observe that any valid sequence of <animals> must either begin with a <cat> or a <dog> element. The first element can possibly be repeated, but at one point, there has to be the first instance of the other element. So this gives a choice of two possible sequences. After we have ensured that there is at least one <cat> and one <dog> element, there can be any number of additional elements:

<xs:complexType name="animals">
  <xs:sequence>
    <xs:choice>
      <!-- At least one <cat> followed by one <dog> -->
      <xs:sequence>
        <xs:element name="cat" maxOccurs="unbounded"/>
        <xs:element name="dog"/>
      </xs:sequence>
      <!-- At least one <dog> followed by one <cat> -->
      <xs:sequence>
        <xs:element name="dog" maxOccurs="unbounded"/>
        <xs:element name="cat"/>
      </xs:sequence>
    </xs:choice>
    <!-- Any remaining number of <cat> and <dog> -->
    <xs:choice minOccurs="0" maxOccurs="unbounded">
      <xs:element name="cat"/>
      <xs:element name="dog"/>
    </xs:choice>
  </xs:sequence>
</xs:complexType>

对于更复杂的元素类型,建议一次性声明元素,然后在复杂类型中使用 <xs:element ref="elementName"/>.

For more complex element types, it is advisable to declare the elements once, and then use <xs:element ref="elementName"/> in the complex type.

这篇关于多个 XML 元素的 XSD 架构,其中至少有一个元素,以任何顺序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆