请考虑以下Amount值类型属性,该属性标记为可为空的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); }
}
当然,这只是一种解决方法。是否有更简洁的方法来禁止发出空值类型元素?
答案 0 :(得分:132)
尝试添加:
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的更多信息。
答案 1 :(得分:6)
还有另一种方法来获取
<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); }
}
答案 2 :(得分:0)
你可以试试这个:
xml.Replace("xsi:nil=\"true\"", string.Empty);