Default Values

Contact Us or call 1-877-932-8228
Default Values

Default Values

Elements that do not have any children can have default values. To specify a default value, use the default attribute of the xs:element element.

Code Sample:

SimpleTypes/Demos/EmployeeDefault.xsd
<?xml version="1.0"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
---- C O D E   O M I T T E D ----

	<xs:element name="Employee">
		<xs:complexType>
			<xs:sequence>
				<xs:element name="Salary" type="Salary"/>
				<xs:element name="Title" type="JobTitle" default="Salesperson"/>
			</xs:sequence>
		</xs:complexType>
	</xs:element>
</xs:schema>

When defaults are set in the XML schema, the following rules apply for the instance document.

  1. If the element appears in the document with content, the default value is ignored.
  2. If the element appears without content, the default value is applied.
  3. If the element does not appear, the element is left out. In other words, providing a default value does not imply that the element should be inserted if the XML instance author leaves it out.

Examine the following XML instance. The Title element cannot be empty; it requires one of the values from the enumeration defined in the JobTitle simple type. However, in accordance with number 2 above, the schema processor applies the default value of Salesperson to the Title element, so the instance validates successfully.

Code Sample:

SimpleTypes/Demos/MikeSmith.xml
<?xml version="1.0"?>
<Employee xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
	xsi:noNamespaceSchemaLocation="EmployeeDefault.xsd">
	<Salary>90000</Salary>
	<Title/>
</Employee>
Next