XML反序列化IEnumerable类时出错

本文关键字:出错 IEnumerable 反序列化 XML | 更新日期: 2023-09-27 17:59:04

我正在尝试将HistoryRoot类序列化并取消序列化为以下XML格式:

<?xml version="1.0"?>
<HistoryRoot xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <Files>
    <HistoryItem d="2015-06-21T17:40:42" s="file:///D:'cars.txt" />
  </Files>
  <Folders>
    <HistoryItem d="2015-06-21T17:40:42" s="D:'fc'Cars" />
  </Folders>
</HistoryRoot>

这是HistoryRoot、HistoryList和HistoryItem类:

[Serializable]
public class HistoryRoot
{
    public HistoryList
    Files = new HistoryList
    {
        sl = new SortedList<DateTime, string>(),
        list = new List<HistoryItem>(),
        max = 500,
        c = program.M.qFile
    },
    Folders = new HistoryList
    {
        sl = new SortedList<DateTime, string>(),
        list = new List<HistoryItem>(),
        max = 100,
        c = program.M.qFolder
    },
}
[Serializable]
public class HistoryList : IEnumerable
{
    [XmlIgnore]
    public List<HistoryItem> list;
    [XmlIgnore]
    public SortedList<DateTime, string> sl;
    [XmlIgnore]
    public int max;
    [XmlIgnore]
    public ComboBox c;
    public IEnumerator GetEnumerator()
    {
        if (list == null) list = new List<HistoryItem>();
        return list.GetEnumerator();
    }
}
public struct HistoryItem
{
    [XmlAttribute("d")]
    public DateTime D;
    [XmlAttribute("s")]
    public string S;
}

这就是我得到错误的地方:

using (FileStream fs = new FileStream("filepath.xml", FileMode.Open))
    {
        XmlSerializer serializer = new XmlSerializer(typeof(HistoryRoot));
        HistoryRoot h = (HistoryRoot)serializer.Deserialize(fs);
    }

"反映类型'History.HistoryRoot'时出错。"System.Exception{System.InvalidOperationException}
如何修复此错误?感谢

XML反序列化IEnumerable类时出错

为了使用XmlSerializer序列化或反序列化实现IEnumerable的类,类必须具有Add方法。来自文件:

XmlSerializer对实现IEnumerable或ICollection的类进行特殊处理。实现IEnumerable的类必须实现接受单个参数的公共Add方法。Add方法的参数必须与从GetEnumerator返回的值的Current属性返回的类型相同,或者是该类型的基之一。

即使从不反序列化而只序列化,也必须具有此方法,因为XmlSerializer同时为序列化和反序列化生成运行时代码。

该方法实际上不必工作就可以成功序列化,它只需要存在:

    public void Add(object obj)
    {
        throw new NotImplementedException();
    }

(当然,要使de序列化成功,必须实现该方法。)

虽然sbc的答案是正确的,我接受了它,但我现在将HistoryList类更改为这样会更容易:

public class HistoryList : List<HistoryItem> //   <-- Add List<HistoryItem>
{    
    [XmlIgnore]
    public SortedList<DateTime, string> sl;
    [XmlIgnore]
    public int max;
    [XmlIgnore]
    public ComboBox c;
}

然后将HistoryRoot更改为:

[Serializable]
public class HistoryRoot
{
    public HistoryList
    Files = new HistoryList
    {
        sl = new SortedList<DateTime, string>(),
        //list = new List<HistoryItem>(),   <-- Remove this line
        max = 500,
        c = program.M.qFile
    },
    Folders = new HistoryList
    {
        sl = new SortedList<DateTime, string>(),
        //list = new List<HistoryItem>(),   <-- Remove this line
        max = 100,
        c = program.M.qFolder
    },
}