Как десериализовать XML-файл, а затем снова сериализовать, добавив новый элемент в этот файл? - PullRequest
1 голос
/ 08 мая 2011

Мне нужно десериализовать 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 Ответ

1 голос
/ 08 мая 2011

Ваш код десериализации фактически не используется - вы ничего не возвращаете. Измените его на вернуть десериализованный список, например:

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
    }
}

затем в событии click, что-то вроде этого:

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);
    }
}
...