如何反序列化XML文件,然后再次序列化将新项添加到此文件?

时间:2011-05-08 09:14:01

标签: c# asp.net xml-serialization

我需要将xml文件反序列化为List或Array,然后将此List或Array放大到1,然后再次序列化文件,将新对象添加到此XML文件中。

我写了类似的东西,但它不起作用:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Xml;
using System.IO;
using System.Xml.Serialization;

public partial class _Default : System.Web.UI.Page 
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }
    public void deserialize()
    {
        string path = Server.MapPath(Request.ApplicationPath + "/test.xml");
        using (FileStream fs = new FileStream(path, FileMode.Open))
        {
            XmlSerializer ser = new XmlSerializer(typeof(List<Person>));
            List<Person> persons = (List<Person>)ser.Deserialize(fs);
            fs.Close();
            //List<Person> persons1 = ((List<Person>)os.Length + 1);
        }
    }
    protected void Button1_Click(object sender, EventArgs e)
    {
        string path = Server.MapPath(Request.ApplicationPath + "/test.xml");
        if (File.Exists(path))
        {
            deserialize();
        }
        else
        {
            List<Person> o = new List<Person>(TextBox1.Text, TextBox2.Text, int.Parse(TextBox3.Text));
            using (FileStream fs = new FileStream(path, FileMode.Create))
            {
                XmlSerializer ser = new XmlSerializer(typeof(List<Person>));
                ser.Serialize(fs, o);
            }
        }
    }
}

感谢您的帮助:))

1 个答案:

答案 0 :(得分:1)

您的反序列化代码实际上是无操作 - 您没有返回任何内容。将其更改为 return 反序列化列表,如下所示:

private List<Person> Deserialize(string path)
{
    using (FileStream fs = new FileStream(path, FileMode.Open))
    {
        XmlSerializer ser = new XmlSerializer(typeof(List<Person>));
        return (List<Person>) ser.Deserialize(fs);//There is an error in XML document (2, 2). this error i got here
    }
}

然后在点击事件中,如下所示:

protected void Button1_Click(object sender, EventArgs e)
{
    string path = Server.MapPath(Request.ApplicationPath + "/test.xml");
    List<Person> people = File.Exists(path) ? Deserialize(path)
                                            : new List<Person>();
    people.Add(new Person(TextBox1.Text, TextBox2.Text,
                          int.Parse(TextBox3.Text));
    using (FileStream fs = File.OpenWrite(path))
    {
        XmlSerializer ser = new XmlSerializer(typeof(List<Person>));
        ser.Serialize(fs, o);
    }
}