views:

282

answers:

2

This is duplicate of http://stackoverflow.com/questions/306877/can-xmlserializer-deserialize-into-a-nullableint 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.

+3  A: 

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;
    }
}
Cheeso
Seems like a bit of a hassle am I right? See my comment above.
ChaosPandion
Yeah, it's a hassle, but sometimes it's necessary. If you want `<number/>`, and not `<number xs:nil='true'/>`, then you need to do extra work.
Cheeso
A: 

You could always do a string replace on the final xml output.

Replace(" i:nil=\"true\"/>","/>");

Generally, it is a bad idea to try to hack at xml with string manipulation, but the replace above is safe and will always convert <anything i:nil="true"/> to <anything/>.

It's a hack, but an acceptable one considering the alternative.

Ryan
-1: what if a different prefix is used for the namespace that "nil" is in? What if the namespace declaration happens to be present on that element?
John Saunders