views:

122

answers:

2

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.

A: 

I don't know if it is possible in your case / situation, but have you already though on using the XML serialization classes, and deserialize the XML by the XmlSerializer classes directly into instances of your custom class, instead of doing it all manually ?

Frederik Gheysels
Yes, I have. But because the input can be in several formats and some custom logic has to be done, the standard serialization doesn't work. Besides that, I never had the out of the box serialization work. It really is too limited.
borisCallens
+1  A: 

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).

Marc Gravell