Search code examples
c#xelement

Does XElement have built in support for nil=true


I have the following xml parsed into an XElement named entry.

<Person>
  <Name>Ann</Name>
  <Age i:nil="true" xmlns:i="http://www.w3.org/2001/XMLSchema-instance" />
</Person>

When fetching the age property I write this:

        var entry =
            XElement.Parse(
                "<Person><Name>Ann</Name><Age i:nil=\"true\" xmlns:i=\"http://www.w3.org/2001/XMLSchema-instance\" /></Person>");
        var age = entry.Element("Age").Value;

age is now "", and I wonder if there is some kind of build in way to get a null instead of ""?

Most searches talk about if the entry isn't in the xml, but I always have the nulls filled out like this.


Solution

  • No, I don't believe there's anything for this, but it would be dead easy to write an extension method:

    private static readonly XNamespace ns = "http://www.w3.org/2001/XMLSchema-instance";
    
    public static string NilAwareValue(this XElement element)
    {
        XAttribute nil = element.Attribute(ns + "nil");
        return nil != null && (bool) nil ? null : element.Value;
    }
    

    Or using the nullable bool conversion:

    public static string NilAwareValue(this XElement element)
    {
        return (bool?) element.Attribute(ns + "nil") ?? false ? null : element.Value;
    }