Mark Bostleman
Mark Bostleman

Reputation: 2205

XmlSerializer deserialize attribute with empty string to zero

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?

Upvotes: 2

Views: 2026

Answers (1)

kbrimington
kbrimington

Reputation: 25642

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); }
}

Upvotes: 2

Related Questions