Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 692
Mark Bostleman Avatar asked Aug 03 '26 13:08

Mark Bostleman


1 Answers

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); }
}
like image 93
kbrimington Avatar answered Aug 06 '26 01:08

kbrimington



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!