从.NET 3.5更新到.NET 4.6后的XmlSerializer错误

时间:2019-02-11 13:41:29

标签: c# xml serialization xml-serialization

所以我最近将一个项目从.NET 3.5更新到了.NET 4.6,我的XML序列化停止了工作。我同意将它缩小为一个看起来很奇怪的单一结构。

[XmlElement("price1", typeof(PriceBonusData))]
[XmlElement("price2", typeof(PriceBonusData))]
public List<PriceBonusData> PriceBonusDataList;

该错误表明我需要向该字段添加XmlChoiceIdentifier属性,但是无论我如何添加它,它仍然不起作用。似乎奇怪的是,它确实可以在.NET 3.5上运行,所以为什么突然需要新属性?

编辑:这是我尝试使用XmlChoiceIdentifier的尝试。我在文档和SO上都看到了类似的解决方案,但它似乎对我不起作用。

[XmlElement(IsNullable = false)]
[XmlIgnore]
public ItemChoiceType[] ItemTypeArray = (ItemChoiceType[])Enum.GetValues(typeof(ItemChoiceType));

[XmlChoiceIdentifier("ItemTypeArray")]
[XmlElement("price1", typeof(PriceBonusData))]
[XmlElement("price2", typeof(PriceBonusData))]
public List<PriceBonusData> PriceBonusDataList;

[XmlType(IncludeInSchema = false)]
public enum ItemChoiceType
{
    [XmlEnum("price1")]
    price1,
    [XmlEnum("price2")]
    price2
}

Edit2:我对.NET 3.5版本的空项目进行了一些进一步的测试,所以我想我可以分享它在工作时的行为。

此结构使用最后一个XmlElement(在本例中为“ price2”)进行序列化。

反序列化期间,两个元素均有效。我手动更改了XML文件,使其同时包含“ price1”和“ price2”,并正确地反序列化了它们。

1 个答案:

答案 0 :(得分:1)

如果您只是想反序列化,那么这可能对您有用:

public class Foo
{
    // the "real" list that takes <price1> elements
    [XmlElement("price1", typeof(PriceBonusData))]
    public List<PriceBonusData> PriceBonusDataList {get;} = new List<PriceBonusData>();

    // spoof a second list that handles <price2> elements (actually: the same list)
    [XmlElement("price2", typeof(PriceBonusData))]
    public List<PriceBonusData> PriceBonusDataList2 => PriceBonusDataList;

    // this disables serialization of PriceBonusDataList2 so we don't double up
    public bool ShouldSerializePriceBonusDataList2() => false;
}

缺点是,如果您对它进行序列化,则所有内容都会变成<price1>,无论它是以<price1>还是<price2>开头的。 ...我看不到任何解决方法,因为没有地方可以存储它的原始内容。