Suppress Null Value Types from Being Emitted by XmlSerializer

前端 未结 3 419
野的像风
野的像风 2020-11-29 17:53

Please consider the following Amount value type property which is marked as a nullable XmlElement:

[XmlElement(IsNullable=true)] 
public double? Amount { ge         


        
3条回答
  •  Happy的楠姐
    2020-11-29 18:20

    Try adding:

    public bool ShouldSerializeAmount() {
       return Amount != null;
    }
    

    There are a number of patterns recognised by parts of the framework. For info, XmlSerializer also looks for public bool AmountSpecified {get;set;}.

    Full example (also switching to decimal):

    using System;
    using System.Xml.Serialization;
    
    public class Data {
        public decimal? Amount { get; set; }
        public bool ShouldSerializeAmount() {
            return Amount != null;
        }
        static void Main() {
            Data d = new Data();
            XmlSerializer ser = new XmlSerializer(d.GetType());
            ser.Serialize(Console.Out, d);
            Console.WriteLine();
            Console.WriteLine();
            d.Amount = 123.45M;
            ser.Serialize(Console.Out, d);
        }
    }
    

    More information on ShouldSerialize* on MSDN.

提交回复
热议问题