开发者

How to deserialize XML file and then serialize again adding new item to this file?

开发者 https://www.devze.com 2023-03-03 13:14 出处:网络
I need to deserialize xml file to List or Array then enlarge this List or Array on 1, then serialize again file adding new object to this XML file.

I need to deserialize xml file to List or Array then enlarge this List or Array on 1, then serialize again file adding new object to this XML file.

I wrote something like that but it's don't work:

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开发者_Python百科.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);
            }
        }
    }
}

thanks for any help:)


Your deserialization code is effectively a no-op - you're not returning anything. Change it to return the deserialized list, like this:

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

then within the click event, something like this:

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

精彩评论

暂无评论...
验证码 换一张
取 消