XLinq xsi:nil="true"

I was wondering if there was any consideration about providing "first-class" support for indicating that the content of an XElement equates to "nil". The XML Schema spec is pretty clear that you can only use xsi:nil="true" when the element contains no content. But to detect this, you currently have to do a nested if{}:

if (x.Element(_SupplierID).Attribute(_nil) != null)
{
. if (x.Element(_SupplierID).Attribute(_nil).Value == "true"
)
. {
. nilCount++;
. }
}

It would be nice is there was an easier way to test for the xsi:nil case -- just as there is for missing elements: if (x.Element("Name")==null){}. That would make it easier to use case statements to process nodes.

Thanks,

- Erik




Answer this question

XLinq xsi:nil="true"

  • BareFootinBoy

    (xElement.IsNil), or (xElement == XLinq.Nil) perhaps I think the problem with x.Element(...) == null is that the nullity is a reference nullity, not a scalar nullity.



  • Steve_J

    An easier way to do the xsi:nil test is

    XName nil = "{http://www.w3.org/2001/XMLSchema-instance}nil";
    XElement e = XElement.Parse(@"
    <root xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'>
    <foo xsi:nil='true'/>
    </root>");

    if ((string)e.Element("foo").Attribute(nil) == "true") Console.WriteLine("nil");

    When you cast an XAttribute to string, the result is null if the attribute isn't there, so the test above will be true only if an xsi:nil attribute is present and has the value "true".


  • XLinq xsi:nil="true"