The following illustrates how a default value is specified for an element in the XSD is dealt with within the generated code behaves as following
XSD |
Copy Code
|
---|---|
<xs:element name="RootElm"> <xs:complexType> <xs:sequence> <xs:element name="OptionalIntDef" type="xs:integer" minOccurs="0" default="99" /> <xs:element name="RequiredIntDef" type="xs:integer" minOccurs="1" default="66" /> </xs:sequence> </xs:complexType> </xs:element> |
XML | Object Model Value |
<RootElm> <OptionalIntDef>123</OptionalIntDef> <RequiredIntDef>456</RequiredIntDef> <RootElm> |
OptionalIntDef=123 RequiredIntDef=456 |
<RootElm> <RequiredIntDef>456</RequiredIntDef> <RootElm> |
OptionalIntDef=null RequiredIntDef=456 |
<RootElm> <OptionalIntDef/> <RequiredIntDef/> <RootElm> |
OptionalIntDef=99 RequiredIntDef=66 |
The following illustrates how a default value is specified for an element in the XSD is dealt with within the generated code behaves as following
XSD |
Copy Code
|
---|---|
<xs:element name="Root"> <xs:complexType> <xs:attribute name="OptionalIntegerDef" default="5" type="xs:integer" /> </xs:complexType> </xs:element> |
XML | Object Model Value |
<RootElm OptionalIntegerDef="123"/> | OptionalIntegerDef=123 |
<RootElm/> | OptionalIntegerDef=5 |
XSD Spec see http://www.w3.org/TR/xmlschema-0/#OccurrenceConstraints
Default values of both attributes and elements are declared using the default attribute, although this attribute has a slightly different consequence in each case. When an attribute is declared with a default value, the value of the attribute is whatever value appears as the attribute's value in an instance document; if the attribute does not appear in the instance document, the schema processor provides the attribute with a value equal to that of the default attribute. Note that default values for attributes only make sense if the attributes themselves are optional, and so it is an error to specify both a default value and anything other than a value of optional for use.
The schema processor treats defaulted elements slightly differently. When an element is declared with a default value, the value of the element is whatever value appears as the element's content in the instance document; if the element appears without any content, the schema processor provides the element with a value equal to that of the default attribute. However, if the element does not appear in the instance document, the schema processor does not provide the element at all. In summary, the differences between element and attribute defaults can be stated as: Default attribute values apply when attributes are missing, and default element values apply when elements are empty.