makes
makes

Reputation: 6548

Understanding xsd:choice and minOccurs

I am having trouble understanding the behavior of the following XML schema:

<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <xsd:element name="rootnode">
    <xsd:complexType>
      <xsd:sequence>
        <xsd:choice minOccurs="1" maxOccurs="2">
          <xsd:element name="e1" minOccurs="1" maxOccurs="2"/>
          <xsd:element name="e2" minOccurs="0" maxOccurs="1"/>
        </xsd:choice>
      </xsd:sequence>
    </xsd:complexType>
  </xsd:element>
</xsd:schema>

I expected at least one instance of either element <e1> or <e2> be required as a child of <rootnode>. Despite my expectations, an empty <rootnode> will validate against this schema:

 > xmllint --schema test.xsd empty.xml
 <?xml version="1.0" encoding="UTF-8"?>
 <rootnode>
 </rootnode>
 empty.xml validates

If I change the minOccurs attribute of element e2 to something other than "0", I get the behavior I originally expected.

Upvotes: 38

Views: 24017

Answers (2)

David W
David W

Reputation: 945

Here are the allowable combinations

Two choices:
e1 (1 - 2) + e1 (1 - 2) = e1 x (2 - 4), or
e1 (1 - 2) + e2 (0 - 1), or 
e2 (0 - 1) + e1 (1 - 2), or
e2 (0 - 1) + e2 (0 - 1) = e2 (0 - 2)

One choice (but no new outcomes):
e1 (1-2), or
e2 (0-1)


e1e1, e1e1e1, e1e1e1e1
e1, e1e2, e1e1e2 
e2e1, e2e1e1 
empty, e2, e2e2 

Note that choice[min=2 max=2] would have produced the same set of valid combinations.

Upvotes: 2

Michael Kay
Michael Kay

Reputation: 163322

I tell you you can go to the shops at least once and at most twice, and each time you have a choice of what to buy: you can buy apples (either one apple or two apples), or you can buy oranges (either no oranges or one orange).

It's entirely possible that you will choose to go to the shops twice and on each occasion to buy no oranges. So you come back with nothing.

Upvotes: 105

Related Questions