【发布时间】:2009-08-18 20:55:56
【问题描述】:
请考虑以下标记为可空 XmlElement 的金额值类型属性:
[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); }
}
当然,这只是一种解决方法。是否有更简洁的方法来抑制发出空值类型元素?
【问题讨论】:
-
顺便说一句; “金额”(用于付款)可能更适合
decimal。 -
优点:浮点货币是邪恶的。
-
@Marc 也感谢您指出这一点。
-
你的方案不错,我也用。然而,马克的答案更好......
标签: c# xml xml-serialization