简体   繁体   中英

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

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM