我有以下类结构我想序列化到XML:冗余元素序列化类时为XML叶元素属性
public class Foo
{
[XmlArray("approxPriceList")]
[XmlArrayItem("approxPrice")]
public List<ApproxPriceElement> ApproxPriceList { get; set; }
}
public class ApproxPriceElement
{
[XmlAttribute("currency")]
public string Currency { get; set; }
[XmlElement("approxPrice")]
public decimal? ApproxPrice { get; set; }
}
如果我序列Foo
,我得到以下XML:
<approxPriceList>
<approxPrice currency="aud">
<approxPrice>2220.00</approxPrice>
</approxPrice>
</approxPriceList>
我想是这样的:
<approxPriceList>
<approxPrice currency="aud">2220.00</approxPrice>
</approxPriceList>
唯一的想法是将Foo
中的ApproxPriceList
更改为List<decimal?>
,但我无法弄清楚如何将currency
属性与列表中的每个approxPrice
关联起来。
有没有办法做到这一点?
这似乎只在我使用非空值时才起作用,即'decimal'而不是'decimal?'。否则,当我序列化时,我得到一个异常,表明'XmlText'不能用于复杂类型。 – LeopardSkinPillBoxHat 2013-04-22 01:07:20
@LeopardSkinPillBoxHat我已经更新了答案,检查它是否修复了问题 – nmat 2013-04-22 01:16:38
不,我得到了同样的错误“Can not serialize member'ApproxPrice'of System.Nullable'1 [System.Decimal]。XmlAttribute/XmlText无法使用编码复杂类型“。 我想我有一个解决方法:(1)将属性更改为不可为空; (2)将'ShouldSerializeApproxPrice'方法添加到'ApproxPrice'属性,如果该属性设置为特殊值(例如-1)则返回false。 – LeopardSkinPillBoxHat 2013-04-22 01:40:47