How to exclude null properties when using XmlSerializer

前端 未结 9 1570
谎友^
谎友^ 2021-02-02 07:11

I\'m serializing a class like this

public MyClass
{
    public int? a { get; set; }
    public int? b { get; set; }
    public int? c { get; set; }
}
         


        
9条回答
  •  礼貌的吻别
    2021-02-02 07:50

    You ignore specific elements with specification

    public MyClass
    {
        public int? a { get; set; }
    
        [System.Xml.Serialization.XmlIgnore]
        public bool aSpecified { get { return this.a != null; } }
    
        public int? b { get; set; }
        [System.Xml.Serialization.XmlIgnore]
        public bool bSpecified { get { return this.b != null; } }
    
        public int? c { get; set; }
        [System.Xml.Serialization.XmlIgnore]
        public bool cSpecified { get { return this.c != null; } }
    }
    

    The {field}Specified properties will tell the serializer if it should serialize the corresponding fields or not by returning true/false.

提交回复
热议问题