Keep forgetting that xsi:nil causes schema validation found non-data type errors
I have been facing this error everytime I start an InfoPath project, and I keep forgetting the reason why. I mean I got the answer for this during Beta 2 timeframe, and it still doesn't get into my head...
InfoPath Team blog has posted the reason why here. It is because a nillable attribute is typically present when the following data types are null:
- Whole Number (integer)
- Decimal (double)
- Date (date)
- Time (time)
- Date and Time (dateTime)
Setting the above types with certain values without removing the attribute will cause schema validation error. The team blog has provided a generic function to remove the nillable attribute, but do you know that you have to put the attribute back when you want to set that same element back to null? So I'm going to provide you the generic function to insert back the nillable attribute. And for completeness sake, I'm going to copy the generic delete function here as well.
public void DeleteNil(XPathNavigator node)
{
if (node.MoveToAttribute("nil", "http://www.w3.org/2001/XMLSchema-instance"))
{
node.DeleteSelf();
}
}
public void InsertNil(XPathNavigator node)
{
if (!node.MoveToAttribute("nil", "http://www.w3.org/2001/XMLSchema-instance"))
{
node.CreateAttribute("xsi", "nil", "http://www.w3.org/2001/XMLSchema-instance", "true");
}
}
When you want to set the node with certain value,
DeleteNil(xpathMyNode);
xpathMyNode.SetValue(DateTime.Today.ToString());
When you want to set the node to empty,
xpathMyNode.SetValue(string.Empty);
InsertNil(xpathMyNode);