in

SharePoint Blogs

The Best Place for SharePoint-related Blogs

dooke's Sharepoint place

  • The xsi:nil attribute, the correct way

    You find a lot of information about the issues of the xsi:nil attribute when using Infopath.

    yust a quick reminder if you do not know wat the problem is:

    if you attempt to programmatically set a value on a node that has a nillable attribute, Infopath will throw an error : “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)

    What you don't find is a good method that will reinsert the nillable atribute what you set your node value back to true.

    For deleting the attribute, a generic method is presented on more then one blog:

    public void DeleteNil(XPathNavigator node){if (node.MoveToAttribute("nil", "http://www.w3.org/2001/XMLSchema-instance"))      node.DeleteSelf();

    }

    When using this method, the attribute will be deleted so you can programmically set a value:

    XPathNavigator navigator = this.MainDataSource.CreateNavigator(); 

    //Create a navigator for the fieldnode

    //where we want to set the value in codeXPathNavigator node = navigator.SelectSingleNode("/my:myFields/my:myint", this.NamespaceManager); 

    //Check if the attribute exists on this node

    //and if it exists, delete it

    DeleteNil(node);

     

    but then comes the tricky part. Suppose you want to reinsert the nillable back to the node if you want to set your value back to nill. I've found some methods out there but they not quit finished.

     

    if you insert a value, Infopath rewrites the xml with a value between the tags:

    Original: <my:myint />

    Outcome: <my:myint>1</my:myint>

     

    When you want to insert a nillable back into the node you need to delete the closing tag back like the original.

     

    Here's the method who does that:

    public static void InsertNil(XPathNavigator node)

    {

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

    {

    Match m = Regex.Match(node.OuterXml, @"^<.+?></.+?>");if (m.Success)

    {

    string result = string.Empty;

    result = Regex.Replace(node.OuterXml, @"</.+?>", "", RegexOptions.IgnoreCase);result = Regex.Replace(result, @">", "/>", RegexOptions.IgnoreCase);

    node.OuterXml = result;

    }

    node.CreateAttribute(
    "xsi", "nil", "http://www.w3.org/2001/XMLSchema-instance", "true");

    }

    }


Need SharePoint Training? Attend a SharePoint Bootcamp!

Posts (c) their respective authors. Everything else (c) 2007 SharePoint Experts