XML Schema Cardinality: minOccurs and maxOccurs Guide
In XML Schema Definition (XSD), the minOccurs and
maxOccurs attributes define the cardinality of elements,
establishing how many times an element can appear within an XML instance
document. By configuring these two attributes, schema authors enforce
data structure constraints ranging from optional fields and mandatory
single occurrences to repeatable lists and unbounded collections.
Default Behavior
If either minOccurs or maxOccurs is omitted
from an element declaration, XML Schema automatically assigns a default
value of 1.
- An element declared as
<xs:element name="title" type="xs:string"/>is functionally identical to<xs:element name="title" type="xs:string" minOccurs="1" maxOccurs="1"/>. - Under default settings, the element is strictly mandatory and can appear exactly once.
Understanding
minOccurs
The minOccurs attribute specifies the minimum number of
times an element must appear. Its value must be a non-negative integer
(0, 1, 2, etc.).
minOccurs="0": Makes the element optional. If the element is omitted from the XML document, validation succeeds.minOccurs="1": Makes the element mandatory. It must appear at least once.minOccurs="N"(where N > 1): Requires the element to appear at leastNtimes.
Understanding
maxOccurs
The maxOccurs attribute specifies the maximum number of
times an element is permitted to appear. Its value can be a non-negative
integer or the string literal "unbounded".
maxOccurs="1": Restricts the element to at most one occurrence.maxOccurs="N"(where N > 1): Allows the element to appear up toNtimes.maxOccurs="unbounded": Removes any upper limit on occurrences, allowing the element to repeat indefinitely.
Common Cardinality Patterns
- Mandatory, Exactly Once (Default)
minOccurs="1"maxOccurs="1"- The element must appear once and cannot repeat.
- Optional, At Most Once
minOccurs="0"maxOccurs="1"- The element may appear once or be omitted entirely.
- Zero or More (Optional List)
minOccurs="0"maxOccurs="unbounded"- The element can be omitted or repeated any number of times.
- One or More (Required List)
minOccurs="1"maxOccurs="unbounded"- The element must appear at least once and may repeat without limit.
Usage on Model Groups
In addition to individual <xs:element>
definitions, minOccurs and maxOccurs can be
applied to compositor groups such as <xs:sequence>
and <xs:choice>.
- Applying
minOccurs="0"to an<xs:sequence>makes the entire sequence of child elements optional as a block. - Applying
maxOccurs="unbounded"to an<xs:choice>allows any combination of the choices to repeat indefinitely.
Note: The <xs:all> compositor restricts both
minOccurs and maxOccurs to values of
0 or 1 only.