XSD schema for multiple XML elements with at least one present, in any order

淺唱寂寞╮ 提交于 2021-02-08 11:31:24

问题


This is my XML:

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

<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.

This is what I tried:

<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.


回答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>

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>

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



来源:https://stackoverflow.com/questions/41484694/xsd-schema-for-multiple-xml-elements-with-at-least-one-present-in-any-order

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!