Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can XmlSerializer deserialize into a Nullable<int>?

This is duplicate of Can XmlSerializer deserialize into a Nullable<int>? but I need a solution that neither change xml document nor forces me to implement IXmlSerializable interface. I dont want to implement IXmlSerializable because I have many additional elements beside <number> that get deserialized correctly.

My xml can contain either element <number>4</number> or <number/>

<root>
...
either <number>4</number> or <number/>
... [other elements]
</root>

Class

public class root
{
public int? number {get; set;}
...
}

does not work.

like image 653
jlp Avatar asked Dec 16 '09 11:12

jlp


1 Answers

You can just use a surrogate property.

public class MyType1
{
    // XmlIgnore means it is not directly serialized
    [XmlIgnore]
    public int? number
    {
        get; set;
    }

    // acts as a surrogate for the nullable property
    [XmlElement("number")]
    public string _number_Surrogate
    {
        get
        {
            return (number.HasValue) ? number.ToString() : "";
        }
        set
        {
            if (!value.Equals(""))
            {
                number = Int32.Parse(value);
            }
        }
    }

    public System.DateTime Time
    {
        get; set;
    }
}
like image 82
Cheeso Avatar answered Nov 15 '22 12:11

Cheeso