views:

14

answers:

1

I would like to use XmlSerializer and deserialize attributes with empty string values into zeros for ints. Every question I've seen regarding deserializing attributes with empty strings involves setting nullable ints to null - but I want to set non-nullable ints to zero, not null.

Is there any easy way to do this without implementing IXmlSerializable and just handling it all myself?

A: 

One approach could be to configure a dummy serializable property, and use a different property in practice:

private int myint;

[XmlIgnore]
public int MyInt { get; set; }

[XmlElement("MyInt")]
public string MyIntString
{
    get { return this.MyInt.ToString(); }
    set { this.MyInt = Convert.ToInt32(value ?? string.Empty); }
}
kbrimington
Thanks for the reply. Actually, I had already tried the first approach listed above but XmlSerializer throws an InvalidOperationException with the message "Cannot serialize member 'MYPROPERTY' of type System.Nullable`1[System.Int32]. XmlAttribute/XmlText cannot be used to encode complex types."I could just make MYPROPERTY a string and create a method that tries to cast to an int - but I hadn't taken it that far yet because I was still holding out hope for a simpler approach. Maybe I am doing something else wrong?
MarkB
Oh, you're right. I've grown accustomed to WCF, which handles these types easier. Back in the day, what I would do is use a dummy property as a string, and parse it into my real property. I'll update the post accordingly.
kbrimington
Awesome thanks! That looks like cleanest approach. Too bad there isn't something like [XmlAttributeAttribute(EmptyValue="0")] :)
MarkB