Suppress Null Value Types from Being Emitted by XmlSerializer

前端 未结 3 422
野的像风
野的像风 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条回答
  • 2020-11-29 18:00

    There is also an alternative to get

     <amount /> instead of <amount xsi:nil="true" />
    

    Use

    [XmlElement("amount", IsNullable = false)]
    public string SerializableAmount
    {
        get { return this.Amount == null ? "" : this.Amount.ToString(); }
        set { this.Amount = Convert.ToDouble(value); }
    }
    
    0 讨论(0)
  • 2020-11-29 18:13

    you can try this :

    xml.Replace("xsi:nil=\"true\"", string.Empty);

    0 讨论(0)
  • 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.

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