抑制XmlSerializer发出的空值types

请考虑以下金额值types属性被标记为可空的XmlElement:

[XmlElement(IsNullable=true)] public double? Amount { get ; set ; } 

当一个可为空的值types设置为null时,C#XmlSerializer结果如下所示:

 <amount xsi:nil="true" /> 

而不是发射这个元素,我想XmlSerializer完全抑制元素。 为什么? 我们使用Authorize.NET进行在线支付,如果存在null元素,Authorize.NET将拒绝请求。

当前的解决scheme/解决方法是根本不序列化数值types属性。 相反,我们创build了一个补充属性SerializableAmount,它基于Amount并被序列化。 由于SerializableAmount是Stringtypes的,如果默认情况下为null,那么类似的引用types被XmlSerializer所抑制,所以一切正常。

 /// <summary> /// Gets or sets the amount. /// </summary> [XmlIgnore] public double? Amount { get; set; } /// <summary> /// Gets or sets the amount for serialization purposes only. /// This had to be done because setting value types to null /// does not prevent them from being included when a class /// is being serialized. When a nullable value type is set /// to null, such as with the Amount property, the result /// looks like: &gt;amount xsi:nil="true" /&lt; which will /// cause the Authorize.NET to reject the request. Strings /// when set to null will be removed as they are a /// reference type. /// </summary> [XmlElement("amount", IsNullable = false)] public string SerializableAmount { get { return this.Amount == null ? null : this.Amount.ToString(); } set { this.Amount = Convert.ToDouble(value); } } 

当然,这只是一个解决方法。 有一个更清晰的方法来抑制空值types元素被发射?

尝试添加:

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

框架的一部分有许多模式。 有关信息, XmlSerializer还查找public bool AmountSpecified {get;set;}

完整的例子(也切换到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); } } 

有关MSDN上ShouldSerialize *的更多信息。

还有一个替代scheme

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

使用

 [XmlElement("amount", IsNullable = false)] public string SerializableAmount { get { return this.Amount == null ? "" : this.Amount.ToString(); } set { this.Amount = Convert.ToDouble(value); } } 

你可以试试这个:

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