When an optional element is left out of an XML instance, it has no clear meaning. For example, suppose a schema declares a Name element as having required FirstName and LastName elements and an optional MiddleName element. And suppose a particular instance of this schema does not include the MiddleName element. Does this mean that the instance author did not know the middle name of the person in question or does it mean the person in question has no middle name?
Setting the nillable attribute of xs:element to true indicates that such elements can be set to nil by setting the xsi:nil attribute to true.
<?xml version="1.0"?> <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"> <xs:element name="Author"> <xs:complexType> <xs:sequence> <xs:element name="FirstName" type="xs:string"/> <xs:element name="MiddleName" type="xs:string" nillable="true"/> <xs:element name="LastName" type="xs:string"/> </xs:sequence> </xs:complexType> </xs:element> </xs:schema>
<?xml version="1.0"?> <Author xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="AuthorNillable.xsd"> <FirstName>Mark</FirstName> <MiddleName xsi:nil="true"/> <LastName>Twain</LastName> </Author>
By including the
MiddleName element and setting
xsi:nil to true, we are explicitly stating that we do not know anything about Mark Twain's middle name. He might have had one, but we don't know what it is, and if we do, we're not saying.
This is, of course, somewhat strange. It implies that if we had simply left the
MiddleName out, we would be indicating that Mark Twain has no middle name. The important thing is that the application consuming your XML data can differentiate between nil values, empty elements, and missing elements.