XML Schema Tutorials - Herong's Tutorial Examples
Dr. Herong Yang, Version 4.10

Overriding Element Type to Empty Content - nillable

This section describes a tutorial example on what is a nillable element and how to declare an element to be nillable.

Sometimes when constructing an element in an XML document, you way want to override the element type defined in the schema to say no element content is provided. This can be done by using the special attribute "nil="true"" to override the content type defined in the schema.

For example, elements representing sales order may defined to have a "shipDate" child element, which must have "date" as its content. However, orders that are not shipped yet will have no content in "shipDate". The "shipDate" element in those orders can use the special attribute "nil="true"".

Rules on overriding the element type to say no element content is provided using the special attribute "nil="true"":

1. The element mus be declared with "nillable="true"" in the schema. Note that "nillable="true"" must be added to the element declaration component, not to the type definition component.

2. Declare a new namespace prefix in the XML document called, "xsi", with a special attribute on the root element: "xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"". This is needed to provide the namespace prefix "xsi" for the next change.

3. In XML document, add the special attribute "xsi:nil="true"" to the element.

4. No content (no child element, or text content) should be include in that element.

5. Attributes of that element is not affected by "xsi:nil="true"".

Below is a tutorial sample schema named order.xsd that has the "shipDate" element declared as "nillable":

<?xml version="1.0"?>
<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<!-- order.xsd
 - Copyright (c) 2007 by Dr. Herong Yang. All rights reserved.
-->

 <xsd:element name="order">
  <xsd:complexType>
   <xsd:sequence>
    <xsd:element name="product" type="xsd:string"/>
    <xsd:element name="price" type="xsd:string"/>
    <xsd:element name="shipDate" type="shipDateType"
       nillable="true"/>
   </xsd:sequence>
  </xsd:complexType>
 </xsd:element>

 <xsd:complexType name="shipDateType">
  <xsd:simpleContent>
   <xsd:extension base="xsd:date">
    <xsd:attribute name="carrier" type="xsd:string"/>
   </xsd:extension>
  </xsd:simpleContent>
 </xsd:complexType>

</xsd:schema>

Sample XML documents that conforms to this schema are provided in sections below.

Sections in This Chapter

Overriding Element Type to Empty Content - nillable

Overriding Element Type to Empty Content - xsi:nil

Defining a Derived Datatype from a Base Datatype

Overriding the Base Datatype - xsi:type

Overriding the Base Datatype - Errors

Dr. Herong Yang, updated in 2007
Overriding Element Type to Empty Content - nillable