I would be grateful if someone could confirm if the interpretation of the following schema is correct:
<xs:element name="Element1">
<xs:complexType>
<xs:sequence>
<xs:element name="Child1" minOccurs="0" />
<xs:element name="Child2" minOccurs="0" />
</xs:sequence>
</xs:complexType>
</xs:element>
Although both Child1
and Child2
are optional, Element1
has to have at least one child to comply with the above schema; i.e. the document:
<Element1></Element1>
Would not comply. For this to be valid, it would require sequence minOccurs = 0
(?)
Update
The question relates to the meaning of occurrence for sequence (and all) when child elements are optional. For example, the document;
<Element1>
<Child2/>
<Child1/>
</Element1>
Would comply with the above schema. The sequence would have occurred twice; in the first pass, Child1
was absent. In the second, Child2
was absent. But the point is, the sequence minOccurs
(default of 1) was satisfied, because it occurred twice.
With the first example I gave above (just Element1
; no child elements), sequence does not occur at all, and does not (IMO) satisfy minOccurs = 1
.
Must a default XML Sequence (or All) with optional child elements have at least one child?
No...
Although both
Child1
andChild2
are optional,Element1
has to have at least one child to comply with the above schema
The default value for minOccurs
is 1
, so you're correct to assume that the xsd:sequence
is constrained to appear once. However, xsd:sequence minOccurs="1"
is satisfied as long as its children's occurrence constraints are satisfied once. When all child occurrence constraints are minOccurs="0"
, one empty sequence is allowed.
Therefore, <Element1/>
is valid, even without any Child1
or Child2
children elements.
See also
XSD with xs:sequence minOccurs="0"
<xs:element name="r">
<xs:complexType>
<xs:sequence minOccurs="0" maxOccurs="1">
<xs:element name="a"/>
<xs:element name="b"/>
</xs:sequence>
</xs:complexType>
</xs:element>
Valid XML: <r/>
and <r><a/><b/></r>
XSD with xs:sequence minOccurs="1"
(default)
<xs:element name="r">
<xs:complexType>
<xs:sequence minOccurs="1" maxOccurs="1">
<xs:element name="a"/>
<xs:element name="b"/>
</xs:sequence>
</xs:complexType>
</xs:element>
Valid XML: <r><a/><b/></r>
XSD with xs:sequence minOccurs="2"
<xs:element name="r">
<xs:complexType>
<xs:sequence minOccurs="2" maxOccurs="2">
<xs:element name="a"/>
<xs:element name="b"/>
</xs:sequence>
</xs:complexType>
</xs:element>
Valid XML: <r><a/><b/><a/><b/></r>