# Use minOccurs and maxOccurs to control repetition

Source: https://xsdhub.com/learn/xsd-minoccurs-maxoccurs

See how XSD occurrence limits affect missing, optional and repeated elements. Test a complete basket schema and learn why an empty element is not an absent one.

## Count occurrences of the declaration

minOccurs and maxOccurs control how often an element or model group can occur in its enclosing content model. When omitted, both default to 1. Setting minOccurs="0" permits absence; it does not make every possible value valid. maxOccurs="unbounded" removes the fixed upper count for that declaration, while other schema constraints still apply.

## A complete basket schema

The note is optional and occurs at most once. Between one and three sku children must follow it. Each sku uses xs:string, so the schema demonstrates counts and order rather than enforcing a catalogue code format.

```xml
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
  <xs:element name="basket">
    <xs:complexType>
      <xs:sequence>
        <xs:element name="note" type="xs:string" minOccurs="0"/>
        <xs:element name="sku" type="xs:string" minOccurs="1" maxOccurs="3"/>
      </xs:sequence>
    </xs:complexType>
  </xs:element>
</xs:schema>
```

## A basket that passes

This basket has no note and two sku elements. It meets both limits. To test the boundaries, try a single sku, then three, then four. The fourth should fail. Removing all sku elements also fails because the minimum is one.

```xml
<basket>
  <sku>BK-204</sku>
  <sku>PN-018</sku>
</basket>
```

## Optional does not mean empty

Omitting an element is different from including an empty one. An absent optional xs:integer element can be allowed while an empty <quantity/> fails because it has no integer value. An empty xs:string can be allowed unless another restriction forbids it. xsi:nil is a third case and requires a nillable declaration; it is not a general replacement for missing data.

## Repetition still respects sequence

The optional note in this example belongs before the sku children. Putting it at the end fails the sequence even if the element counts look correct. For nested groups, consider both the group occurrence and the declarations inside it; an element maximum is not always a global count across the whole document.

## Choose constraints from the data contract

Do not set every field to optional just to obtain a green result. Work out which fields the consumer needs, how it treats an empty list and whether a practical upper limit is required. Update the schema and producer together, then test zero, one, maximum and above-maximum cases using the same XSD version.

## Primary references

- [W3C XML Schema primer](https://www.w3.org/TR/xmlschema-0/)
