将XML反序列化为对象列表

时间:2013-11-30 19:35:31

标签: c# xml serialization xml-serialization deserialization

我有一个List,我用ToDo对象填充并保存到XML。这非常有效。我将XML反序列化回ToDo对象列表时遇到问题。我知道simillar问题已经很少了,但没有一个能帮助我,因此,我正在写作。

ToDo对象类:

public class ToDo
{
    public string ToDoString;
    public DateTime Date;
}

序列化和反序列化的主程序类和方法:

 static class Program
{
    static List<ToDo> ToDoList = new List<ToDo>();

    public static void Serialize(string toDoString)
    {
        // Create and Initialise the object
        ToDo newToDo = new ToDo();
        newToDo.ToDoString = toDoString;
        newToDo.Date = DateTime.Now;

        // Add the object to the List
        ToDoList.Add(newToDo);

        // Serialize List and save to XML
        XmlSerializer mySerializer = new XmlSerializer(ToDoList.GetType());
        // To write to a file, create a StreamWriter object.
        StreamWriter myWriter = new StreamWriter("myXML.xml");
        mySerializer.Serialize(myWriter, ToDoList);
        myWriter.Close();
    }

    public static void Deserialize()
    {
        // This code was originally wrote to deserialize single object. Now I need to deserialize List of objects and this code doesn't work.
        XmlSerializer myDeserializer = new XmlSerializer(ToDoList.GetType());
        FileStream myFileStream = new FileStream("myXML.xml", FileMode.Open);
        deserializeToDo = (ToDo) // Problems start here
        myDeserializer.Deserialize(myFileStream);
        myFileStream.Close();
    }
}

那么如何将XML反序列化为ToDo对象列表呢?

非常感谢您的帮助。

3 个答案:

答案 0 :(得分:4)

以下为我工作

var loadedData = (List<ToDo>)myDeserializer.Deserialize(myFileStream);

我刚刚在Deserialize

中更改了这一行
XmlSerializer myDeserializer = new XmlSerializer(typeof(List<ToDo>));
FileStream myFileStream = new FileStream("myXML.xml", FileMode.Open);
var loadedData = (List<ToDo>)myDeserializer.Deserialize(myFileStream);
myFileStream.Close();

给你一个提示

public static void Deserialize()
{
    var myDeserializer = new XmlSerializer(typeof(List<ToDo>));
    List<ToDo> ToDoList;
    using (var myFileStream = new FileStream("myXML.xml", FileMode.Open))
    {
        ToDoList = (List<ToDo>)myDeserializer.Deserialize(myFileStream);
    }
}

using块将为您关闭一个流。

答案 1 :(得分:1)

您应该使用以下语句对其进行反序列化:

var deserializedToDoList = (List<ToDo>)myDeserializer.Deserialize(myFileStream);

那应该做的工作。

答案 2 :(得分:1)

删除带注释的代码行//问题从此处开始。

捕获myDeserializer.Deserialize(myFileStream)的输出,如下所示:

public static void Deserialize()
{
    XmlSerializer myDeserializer = new XmlSerializer(ToDoList.GetType());
    FileStream myFileStream = new FileStream("myXML.xml", FileMode.Open);
    var listOfTodos = (List<ToDo>)myDeserializer.Deserialize(myFileStream);
    myFileStream.Close();
}