请考虑以下标记为可为 null 的 XmlElement 的 Amount 值类型属性:
[XmlElement(IsNullable=true)]
public double? Amount { get ; set ; }
当可空值类型设置为 null 时,C# XmlSerializer 结果如下所示:
<amount xsi:nil="true" />
我希望 XmlSerializer 完全抑制该元素,而不是发出该元素。为什么?我们使用 Authorize.NET 进行在线支付,如果存在此 null 元素,Authorize.NET 将拒绝请求。
当前的解决方案/解决方法是根本不序列化 Amount 值类型属性。相反,我们创建了一个补充属性 SerializableAmount,它基于 Amount 并被序列化。由于 SerializableAmount 是 String 类型,如果默认情况下为 null,它就像引用类型一样被 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: >amount xsi:nil="true" /< 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); }
}
当然,这只是一种解决方法。有没有更简洁的方法来抑制 null 值类型元素被发出?
最佳答案
尝试添加:
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);
}
}
有关 ShouldSerialize* on MSDN 的更多信息.
关于c# - 禁止 XmlSerializer 发出空值类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1296468/