Suppress Null Value Types from Being Emitted by XmlSerializer
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.
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); }
}