XSD: what is the significance of minOccurs="0" and defaultValue="x"

11,978

The default value declared for test1 in your schema fragment has the effect of causing a schema processor to treat <test1/> as effectively synonymous with <test1>x</test1>. It does not cause a schema processor to treat your sample instance as synonymous with

<myType>
  <test1>x</test1>
  <test2>dsjhfdshflk</test2>
</myType>

This disappoints some users who would prefer that the default value be supplied whenever the element does not appear at all.

The reason is that in general, elements are not restricted to appearing at most once, or in at most a single location among the children. If the xs:sequence in your type definition were replaced with an xs:choice with maxOccurs='unbounded', a language that proposed to supply <test1>x</test1> wherever test1 could appear but didn't would be forced to supply an infinite number of such defaulted test1 elements. That didn't seem like a good idea to the members of the working group that designed XSD.

So why have defaults at all? Sometimes they are convenient, and allowing defaults on elements provides greater parallelism between the treatment of child elements and attributes, which was an explicit goal of some in the responsible working group.

Share:
11,978
Mischa Obrecht
Author by

Mischa Obrecht

Updated on June 04, 2022

Comments

  • Mischa Obrecht
    Mischa Obrecht almost 2 years

    I find myself wondering what the purpose of the defaultValue attribute in XSD is. Consider, for example a complexType

     <xs:complexType name="myType">
        <xs:sequence>
            <xs:element name="test1" type="type1" defaultValue="x" minOccurs="0" maxOccurs="1"/>
            <xs:element name="test2" type="type2"/>
        </xs:sequence>
     </xs:complexType>
    

    I will be able to validate an XML file of the form

    <myType>
      <test2>dsjhfdshflk</test2>
    </myType>
    

    Now what's the point of the defaultValue attribute of <test1> ?

    Thanks a lot in advance

    Mischa

  • Shiv
    Shiv almost 9 years
    Sorry not clear on what the significance of minOccurs is?