Search code examples
c#.netnullablexmlconvert

XmlConvert and nullable results?


In my project I receive an XmlElement of which I have to parse a few properties back to a class.

For mapping these I use the XmlConvert class. But the source being XML there often are empty nodes or nodes that are not readable. Rather then throwing a bunch of errors, I want to get a NULL back to store in my class.

I started making an XmlConvertExtentions class that does things in the following spirit:

public static class XmlConvertExtentions
{
    public static int? ToNullableInt32 (this XmlConvert c, string s){
        try{ return XmlConvert.ToInt32(s); }
        catch{ return null; }
    }
}

I strongly believe that I'm not the first developper in need of such a functionality and I'm wondering if I'm not inventing yet another wheel.
Furthermore I feel like I'm inventing a really ugly wheel. The try catch feels bad. Is there a better way?

--EDIT--
And now I also noticed that it doesn't even work :P
I think it's because you can't extend static classes.


Solution

  • If the node is null or empty, what is s?

    How about just:

    if(string.IsNullOrEmpty(s)) return null;
    return XmlConvert.ToInt32(s);
    

    Note also that LINQ-to-XML has more graceful handling of these conversions (via casts).