Serializing a Nullable in to XML

后端 未结 5 647
灰色年华
灰色年华 2020-12-02 22:34

I am trying to serialize a class several of the data-members are Nullable objects, here is a example

[XmlAttribute(\"AccountExpirationDate\")]
public Nullabl         


        
5条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-02 23:32

    I was stuck into the similar problem. I had a datetime property (as XmlAttribute) in a class which was exposed in the WCF service.

    Below is what I faced and the solution that worked for me : 1) XmlSerializer class was not serialising XmlAttribute of nullable type

    [XmlAttribute]
    public DateTime? lastUpdatedDate { get; set; }
    Exception thrown : Cannot serialize member 'XXX' of type System.Nullable`1. 
    

    2) Some posts suggest to replace [XmlAttribute] with [XmlElement(IsNullable =true)]. But this will serialize the Attribute as an Element which is totally useless. However it works fine for XmlElements

    3) Some suggest to implement IXmlSerializable interface into your class, but that doesn't allow WCF service to be called from WCF consuming application. So this too does not work in this case.

    Solution :

    Don't mark property as nullable, instead use a ShouldSerializeXXX() method to put your constraint.

    [XmlAttribute]
    public DateTime lastUpdatedDate { get; set; }
    public bool ShouldSerializelastUpdatedDate ()
    {
       return this.lastUpdatedDate != DateTime.MinValue; 
       // This prevents serializing the field when it has value 1/1/0001       12:00:00 AM
    }
    

提交回复
热议问题