Sunday, March 13, 2011

Nillability, empty value and omitted element

Sometimes it's bit confusing for the nill value, empty value and omitted element in XML. The following are some points I found during the use of XML which can be helpful to understand these concept.

Nillability in XSD indicates that the value of one element is not set. That is to say that there is no value for this element. XSD has a way to let you specifically define a nil value for an element in the instance document. This is xsi:nill="true" appearing in the element tag. For example:

<length xsi:nil="true"/>
Adding xsl:nil="true" gives the clear message to the document consumer or processor that the value of this element is nil, not set.

In order to have xsi:nil appear in the instance document XSD requires the schma must have xs:nillable="true" for that element,

<xs:element name="length" type="xs:decimal" nillable="true"/>

With nillable="true" added in the schema, when the value is nil for this element xsi:nil must be there to declare its nillness in the instance document otherwise the document will not be validated against the schema.
For example this is one type defined in XSD :
<xs:complexType name="size">
<xs:sequence>
<xs:element name="sizeNo" type="xs:integer" nillable="true"/>
<xs:element name="length" type="xs:decimal" nillable="true"/>
<xs:element name="standard" type="xs:string" nillable="true"/>
<xs:element name="sizeName" type="xs:string" nillable="false"/>
<xs:element name="width" type="xs:integer" nillable="false"/>
</xs:sequence>
</xs:complexType>
Here comes the instance:
<size xml:xsi="http://www.w3.org/2001/XMLSchema-intances">
<sizeNo xsi:nil="true"/> OK. nil value
<length xsi:nil="true"/> OK. nil value
<standard/> OK. not nil value but empty string value
<sizeName/> OK. Cannot benil value but empty string value
<width>20</> OK. Cannot be nil. Having one value
</size>

<size xml:xsi="http://www.w3.org/2001/XMLSchema-intances">
<sizeNo xsi:nil="true"/> OK. nil value
<length xsi:nil="true"/> OK. nil value
<standard/> OK. not nil value but empty string value
<sizeName/> OK. not nil value but empty string value
<width>20</> OK. Cannot be nil. Having one value
</size>



<size xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance%22&gt;
<sizeNo/> Not OK. Need to add xsi:nil="true"
<length/> Not OK. Need to add xsi:nil="true"
<standard xsi:nil="false">20</standard> OK.
<sizeName xsl:nil="true"/> OK. It is not empty string value.
<width/></size> Not OK. Need to add xsi:nil="true"


Different from nil value of the element the element can be omitted from the instance document this is achieved from the attribute xs:minOccurs in the element. Its default value is 1 which means that if not having xs:minOccurs is equaliant to setiing xs:minOccurs=1.
When xs:minOccurs=0 it indicates that this element might be omitted from the instance document completely.

No comments:

Post a Comment