抑制XmlSerializer发出的空值类型

Ben*_*old 63 c# xml xml-serialization

请考虑以下Amount值类型属性,该属性标记为可为空的XmlElement:

[XmlElement(IsNullable=true)] 
public double? Amount { get ; set ; }
Run Code Online (Sandbox Code Playgroud)

当可空值类型设置为null时,C#XmlSerializer结果如下所示:

<amount xsi:nil="true" />
Run Code Online (Sandbox Code Playgroud)

我希望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: &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); }
}
Run Code Online (Sandbox Code Playgroud)

当然,这只是一种解决方法.有没有更简洁的方法来抑制空值类型元素被发射?

Mar*_*ell 132

尝试添加:

public bool ShouldSerializeAmount() {
   return Amount != null;
}
Run Code Online (Sandbox Code Playgroud)

框架的某些部分可识别出许多模式.有关信息,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);
    }
}
Run Code Online (Sandbox Code Playgroud)

有关MSDNShouldSerialize*的更多信息.

  • 这里是ShouldSerialize模式的MSDN参考:http://msdn.microsoft.com/en-us/library/53b8022e(VS.71).aspx (7认同)
  • 哇,这就是我所说的非常模糊的东西.很酷,你找到了它. (5认同)
  • 嗨马克,这就是我喜欢的原因......你学到了这样的东西.我有几个问题.我只能在msdn中找到以下这个功能的文档:http://msdn.microsoft.com/en-us/library/53b8022e.aspx你知道任何*真正的*文档吗?此外,由于此功能的记录很差,我觉得使用它有点脏.使用这样看似无证的功能是否"安全"? (3认同)

mko*_*mko 6

还有另一种选择

 <amount /> instead of <amount xsi:nil="true" />
Run Code Online (Sandbox Code Playgroud)

使用

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