【发布时间】:2011-08-29 05:34:42
【问题描述】:
尝试反序列化 Xml 字符串,但总是遇到以下元素的问题:
<Taxable />
<DefaultPurchasePrice />
我的 C# 代码 sn-p:
[XmlRoot(ElementName = "Product", Namespace = "http://api.test.com/version/1", IsNullable = false)]
public class Product
{
public Guid Guid { get; set; }
public string ProductName { get; set; }
public bool Taxable { get; set; }
public Decimal DefautSellPrice { get; set; }
[XmlElement("DefaultPurchasePrice")]
public string DefaultPurchasePriceElement
{
get
{
if (DefaultPurchasePrice == null)
return String.Empty;
else
return DefaultPurchasePrice.ToString();
}
set
{
if (value == null | value.Length == 0)
DefaultPurchasePrice = null;
else
DefaultPurchasePrice = Convert.ToDecimal(value);
}
}
[XmlIgnore]
public decimal? DefaultPurchasePrice{ get; set;}
}
好像
xsi:nil="true"
XML 中的属性应该可以解决我的问题。但是因为我们使用 REST 服务器提供的 XML 作为 API 测试的一部分。我们无法直接控制如何构造 XML,但我们可以给他们反馈。所以我认为我应该明确要求他们修复他们的 XML,因为这是他们 XML 的问题,对吧?
同时,我可以通过以下代码反序列化单个元素:
[XmlElement("DefaultPurchasePrice")]
public string DefaultPurchasePriceElement
{
get
{
if (DefaultPurchasePrice == null)
return String.Empty;
else
return DefaultPurchasePrice.ToString();
}
set
{
if (value == null | value.Length == 0)
DefaultPurchasePrice = null;
else
DefaultPurchasePrice = Convert.ToDecimal(value);
}
}
[XmlIgnore]
public decimal? DefaultPurchasePrice{ get; set;}
但是 XML 字符串中有很多 null 元素,而且对方可以修复他们的 XML,所以在这种情况下我不需要对我的反序列化代码做任何事情,对吧?
无论如何,我可以在反序列化之前在我的代码中做一些事情,以便 XML 可以为 null 元素提供适当的 xsi:nil="true" 属性,这样我就不需要在我的 C# 代码中做太多事情,但可以快速修复它们的 XML ?
我正在考虑@Ryan 的解决方案,从这里倒数第二个:deserialize-xml-with-empty-elements-in-c,但不确定有没有更好的解决方案?
编辑:
刚刚做了一个小测试,在 XML 空元素中添加 xsi:nill='true' 确实可以与我现有的 C# 代码一起使用。 但是我确实需要确保从 XML 映射的 C# 类对于来自 XML 且 xsi:nill='true' 的那些 null 元素具有可为空的数据类型。但这是有道理的:当某些来自 XML 的数据字段可能是空类型时,我需要将相应的数据类型显式定义为可为空的。我对此感到非常满意,而不是我目前的解决方案。
【问题讨论】: