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

问题描述 投票:2回答:1

所以我最近更新一个项目从.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(在这种情况下,“PRINCE2”)。

在反序列化这两个元素是有效的。我手动更改的XML文件,以便它同时包含“价格1”和“price2”,它正确地反序列化他们。

c# xml serialization xml-serialization
1个回答
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> ...但是...我看不到周围的任何方式,因为没有地方来存储它最初。

© www.soinside.com 2019 - 2024. All rights reserved.