我有一个可以为空的int类?数据类型设置为序列化为xml元素.有没有办法设置它,所以如果值为null,xml序列化程序将不会序列化该元素?
我试图添加[System.Xml.Serialization.XmlElement(IsNullable = false)]属性,但我得到一个运行时序列化异常,说有一个反映类型的错误,因为"IsNullable可能不会设置为'false '对于Nullable类型.考虑使用'System.Int32'类型或从XmlElement属性中删除IsNullable属性."
[Serializable]
[System.Xml.Serialization.XmlRoot("Score", Namespace = "http://mycomp.com/test/score/v1")]
public class Score
{
private int? iID_m;
...
/// <summary>
///
/// </summary>
public int? ID
{
get
{
return iID_m;
}
set
{
iID_m = value;
}
}
...
}
Run Code Online (Sandbox Code Playgroud)
上面的类将序列化为:
<Score xmlns="http://mycomp.com/test/score/v1">
<ID xsi:nil="true" />
</Score>
Run Code Online (Sandbox Code Playgroud)
但对于null的ID,我根本不需要ID元素,主要是因为当我在MSSQL中使用OPENXML时,对于看起来像的元素,它返回0而不是null
请考虑以下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)