XmlSerializer添加数据而不是覆盖

时间:2014-04-10 12:35:18

标签: c# windows-phone-8 stream xml-serialization overwrite

我忙于Windows Phone项目,每次按下按钮时我都会使用XmlSerializer添加数据。不幸的是,xml文件中的数据被覆盖而不是被添加。如何确保添加数据?

这是我的代码:

private void ReadXmlFile()
    {
        try
        {
            using (IsolatedStorageFile myIsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication())
            {
                using (IsolatedStorageFileStream stream = myIsolatedStorage.OpenFile("Progress.xml", FileMode.OpenOrCreate))
                {
                    XmlSerializer serializer = new XmlSerializer(typeof(List<Progress>));
                    List<Progress> data = (List<Progress>)serializer.Deserialize(stream);

                    this.listBox.ItemsSource = data;              
                }
            }
        }
        catch
        {

        }
    }

List<Progress> data = new List<Progress>();
            data.Add(new Progress() { BMI = bmi, Length = Length, Weight = Weight });

            XmlWriterSettings xmlWriterSettings = new XmlWriterSettings();
            xmlWriterSettings.Indent = true;

            using (IsolatedStorageFile myIsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication())
            {
                using (IsolatedStorageFileStream stream = myIsolatedStorage.OpenFile("Progress.xml", FileMode.OpenOrCreate))
                {
                    XmlSerializer serializer = new XmlSerializer(typeof(List<Progress>));
                    using (XmlWriter xmlWriter = XmlWriter.Create(stream, xmlWriterSettings))
                    {
                        serializer.Serialize(xmlWriter, data);
                    }
                }
            }


            ReadXmlFile();

谢谢!

1 个答案:

答案 0 :(得分:0)

XmlSerializer永远不会修改XML,它只是在每次使用时生成一个新的XML。 如果需要修改XML,则应使用XmlDocument或XDocument而不是序列化程序。

实现目标需要以下工作流程:

1)将当前文件读取到XDocument 2)修改XDocument 3)保存XDocumen的内容