Choose between xs:sequence and xs:choice
Published by XSDHub · How our guides and examples are made
Start with the shape the receiver needs
Use sequence when children must follow a declared order. Use choice when the next content must match one of the declared alternatives. Neither automatically means optional or repeatable: occurrence limits belong to the group or declaration that carries them. Pick the structure that expresses the actual data contract.
A sequence containing a choice
A contact must contain name first, then either email or phone. The choice has the default occurrence range of exactly once. Because the two options have different element names, the alternatives are straightforward for the validator to distinguish.
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
<xs:element name="contact">
<xs:complexType>
<xs:sequence>
<xs:element name="name" type="xs:string"/>
<xs:choice>
<xs:element name="email" type="xs:string"/>
<xs:element name="phone" type="xs:string"/>
</xs:choice>
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:schema>A contact that passes
This document chooses email after name. Replacing email with a single phone element also passes. Moving email before name fails the outer sequence. Adding phone after email fails because the choice is already satisfied and does not repeat.
<contact>
<name>Sam</name>
<email>sam@example.com</email>
</contact>The group changes the meaning of repetition
If the choice had maxOccurs="unbounded", multiple alternatives could occur and the same alternative could appear again. That is different from saying exactly one email and exactly one phone in any order. Write sample documents for each allowed shape before choosing group limits; the schema should describe those shapes without accidentally allowing extra combinations.
When order should not matter
XSD 1.0 also has xs:all for restricted unordered content models. Its child element occurrence limits are much narrower than an arbitrary repeated sequence or choice. Do not replace a sequence with all without checking those constraints. Likewise, two alternatives that can match the same incoming element can make a schema ambiguous; schema compilation errors are separate from document validation failures.
Debug the model rather than shuffling at random
Find the parent complexType and read the content model from left to right. Mark which required items have already appeared, which optional ones were skipped and whether a choice has already been used. After changing the producer, validate the entire document again. The examples here use self-contained XSD 1.0, which the XSDHub workbench supports.