Can XmlSerializer deserialize into a Nullable?

后端 未结 2 1054
野趣味
野趣味 2021-01-03 04:13

This is duplicate of Can XmlSerializer deserialize into a Nullable? but I need a solution that neither change xml document nor forces me to implement IXmlSerializ

相关标签:
2条回答
  • 2021-01-03 04:41

    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;
        }
    }
    
    0 讨论(0)
  • 2021-01-03 05:01

    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.

    0 讨论(0)
提交回复
热议问题