3

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?

1 Answer 1

2

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); }
}
Sign up to request clarification or add additional context in comments.

3 Comments

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?
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.
Awesome thanks! That looks like cleanest approach. Too bad there isn't something like [XmlAttributeAttribute(EmptyValue="0")] :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.