The xsi:nil attribute

Have you ever tried to programmatically set a value on a field only to get a “schema validation” error? Many times, this error is caused by the “nillable” attribute being present on the node. The nillable attribute is a special attribute that can appear on an xsd:element within an XML schema. If an element has the xsi:nil attribute specified, it indicates that the element is present but has no value, and therefore no content is associated with it.

However, if you attempt to programmatically set a value on this node and the nillable attribute is present, you will get an error similar to: “Schema validation found non-data type errors.” You will find the nillable attribute is typically present on the following data types:

  • Whole Number (integer)
  • Decimal (double)
  • Date (date)
  • Time (time)
  • Date and Time (dateTime)

To resolve this error, your code will simply need to test if the nil attribute is present and if so, remove that attribute before setting the value on the node. The following sample procedure takes an XpathNavigator object, checks that node for the nil attribute and if it exists deletes the attribute:

public void DeleteNil(XPathNavigator node)

{

if (node.MoveToAttribute("nil", "http://www.w3.org/2001/XMLSchema-instance"))

      node.DeleteSelf();

}

The above procedure is generic - you can easily call this procedure as needed before programmatically trying to set the value of a field. As an example, this code is called from the click event of a button:

//Create a Navigator object for the main data source

XPathNavigator xn = this.MainDataSource.CreateNavigator();

//Create a navigator object for the field (node)

//where we want to set the current date value

XPathNavigator xnfield1 = xn.SelectSingleNode("/my:myFields/my:field1", this.NamespaceManager);

//Check if the "nil" attribute exists on this node

DeleteNil(xnfield1);

//Create a new dateTime object for the current date

DateTime curDate = new DateTime(DateTime.Today.Year, DateTime.Today.Month, DateTime.Today.Day);

//Set the value of field1 to the current date in the

//correct format: yyyy-mm-dd

xnfield1.SetValue(curDate.GetDateTimeFormats().GetValue(5).ToString());

Scott Heim
Support Engineer