InfoPath Forms Services and the xsi:nil in code behind


Yesterday I had the requirement to programmatically add and remove the xsi:nil attribute from an InfoPath 2010 browser form hosted in InfoPath Forms Services in SharePoint 2010.

There are several solutions for adding and removing xsi:nil to be found on the internet, but I’ve found only one that works in both browser and InfoPath client forms, and that’s by replacing the node’s OuterXml.

public const string NIL_PREFIX = "xsi";
public const string NIL_LOCALNAME = "nil";
public const string NIL_NAMESPACE = "http://www.w3.org/2001/XMLSchema-instance";
        
public static void RemoveNil(XPathNavigator node)
{
    if (node.MoveToAttribute(NIL_LOCALNAME, NIL_NAMESPACE))
        node.DeleteSelf();
}

public static void ClearAndSetNil(XPathNavigator node)
{
    XmlDocument doc = new XmlDocument();
    doc.LoadXml(node.OuterXml);

    XmlElement nDoc = doc.DocumentElement;

    XmlAttribute attr = doc.CreateAttribute(NIL_PREFIX, NIL_LOCALNAME, NIL_NAMESPACE);
    attr.Value = BoolHelper.True;

    nDoc.Attributes.Append(attr);
    nDoc.InnerText = String.Empty;

    node.ReplaceSelf(nDoc.OuterXml);
}

All other solutions seem to throw the “Schema validation found non-data type errors” error. Note that the xsi:nil attribute is only required for field types that require a value, such as:

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

 

Related

» The xsi:nil attribute - http://blogs.msdn.com/b/infopath/archive/2006/11/28/the-xsi-nil-attribute.aspx

» How to: Work with the XPathNavigator and XPathNodeIterator Classes - http://msdn.microsoft.com/en-us/library/office/aa945227.aspx

 


Links to this post

Comments

Wednesday, 1 Jun 2016 06:29 by Tim
Had some code to clear a date field, which worked in the client but was mysteriously throwing an error in a published browser form - found lots of forum posts about setting the xsi:nil attribute with .CreateAttribute(), etc, but finally found this post explaining why it's different for a browser form / InfoPath Forms Services - and the solution! I didn't have a reference to BoolHelper, so just used: attr.Value = "true"; Finally working. Thanks Steven.

CAPTCHA Image Validation