相关疑难解决方法(0)

抑制XmlSerializer发出的空值类型

请考虑以下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 …
Run Code Online (Sandbox Code Playgroud)

c# xml xml-serialization

63
推荐指数
2
解决办法
4万
查看次数

标签 统计

c# ×1

xml ×1

xml-serialization ×1