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: >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); }
}
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)
有关MSDN上ShouldSerialize*的更多信息.
还有另一种选择
<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)
归档时间: |
|
查看次数: |
41293 次 |
最近记录: |