Search code examples
xmlxsdxsd-validationxml-validation

XML Schema: Difference between using <xs:all> and not when minOccurs="0"


What is the difference between this (taken from w3schools.com reference for <xs:all>):

<xs:element name="person">
  <xs:complexType>
    <xs:all>
      <xs:element name="firstname" type="xs:string" minOccurs="0"/>
      <xs:element name="lastname" type="xs:string" minOccurs="0"/>
    </xs:all>
  </xs:complexType>
</xs:element>

And this:

<xs:element name="person">
  <xs:complexType>
      <xs:element name="firstname" type="xs:string" minOccurs="0"/>
      <xs:element name="lastname" type="xs:string" minOccurs="0"/>
  </xs:complexType>
</xs:element>

Notice each child element contains minOccurs="0", and notice the lack of the <xs:all> tag in the second example.

As I understand it, if the child elements didn't specify minOccurs="0", then <xs:all> makes it so the entire group can not appear at all. Whereas not using <xs:all> means all child elements have to appear once, because the default value for minOccurs and maxOccurs in an element is 1.

But, when you do specify minOccurs="0" on all the child elements, wouldn't both examples be the same constraint? Don't both mean each element can either appear once or not appear?

I'm not seeing much use for the <xs:all> element. Maybe you can tell me where it is useful.


Solution

  • Your second example is not a valid XSD because xs:element cannot appear as a child of xs:complexType. Let's assume that your second example was actually

    <xs:element name="person">
      <xs:complexType>
        <xs:sequence>
          <xs:element name="firstname" type="xs:string" minOccurs="0"/>
          <xs:element name="lastname" type="xs:string" minOccurs="0"/>
        </xs:sequence>
      </xs:complexType>
    </xs:element>
    

    Then, we can explain when to use which as follows:

    • Use xs:sequence when element ordering is significant.
    • Use xs:all when element ordering is insignificant.

    In both cases, minOccurs="0" means that the associated element is optional.

    So, in your (fixed) case, your xs:all example would allow firstname and lastname to appear as children on person in any order; your xs:sequence example would constrain firstname to appear before lastname as children of person.