XSD all-or-nothing group

Viewed 32

I want to match these two documents:

<a>
  <b/>
</a>

and:

<a>
  <b/>
  <c/>
  <d/>
</a>

That is, there must be either neither of c and d or both of c and d.

I've tried to have a choice of two sequences, but I get: "The content model is not determinist.", I guess because the choice has to be disambiguated on the first element, which is the same for the two different documents.

1 Answers

You can put c and d inside a sequence group with minOccurs=0. Like this:

<element name="a">
  <complexType>
    <sequence>
      <element name="b" />
      <sequence minOccurs="0">
        <element name="c" />
        <element name="d" />
      </sequence>
    </sequence>
  </complexType>
</element>

If you want c and d to be able to appear in any order, you can do this:

<element name="a">
  <complexType>
    <sequence>
      <element name="b" />
      <choice minOccurs="0">
        <sequence>
          <element name="c" />
          <element name="d" />
        </sequence>
        <sequence>
          <element name="d" />
          <element name="c" />
        </sequence>
      </choice>
    </sequence>
  </complexType>
</element>

Obviously, this approach does not scale well if you have more than two members in the group.

Related