Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Understanding xsd:choice and minOccurs

Tags:

xml

xsd

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.

  • It seems as though the mere absence of element <e2> counts as an occurrence of the xsd:choice in my example.

  • If this is the case, then how come this infinite number of occurrences does not violate the maxOccurs limit in my xsd:choice?

like image 889
makes Avatar asked Mar 07 '11 00:03

makes


People also ask

What does minOccurs mean in XSD?

The minOccurs attribute specifies the minimum number of times that the element can occur. It can have a value of 0 or any positive integer. The maxOccurs attribute specifies the maximum number of times that the element can occur.

What is XSD choice?

XSD choice elements exist to specify a number of alternatives of which only one can be present in an XML file. Formerly importing data from XML files which contained choice elements was not fully supported in the Mendix platform but with the release of version 5.14 this has been resolved.

How do you define a choice element in XML?

Definition and Usage XML Schema choice element allows only one of the elements contained in the <choice> declaration to be present within the containing element.

How do you create a choice in XML schemas?

Using <xsd:choice> in an XSD It has to be defined in XML schema definition of a nested XML content. The element in the root schema has to be optional. Add attribute minOccurs="0" on the element to make it optional.


1 Answers

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.

like image 180
Michael Kay Avatar answered Oct 08 '22 04:10

Michael Kay