我忙于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();
谢谢!
答案 0 :(得分:0)
XmlSerializer永远不会修改XML,它只是在每次使用时生成一个新的XML。 如果需要修改XML,则应使用XmlDocument或XDocument而不是序列化程序。
实现目标需要以下工作流程:
1)将当前文件读取到XDocument 2)修改XDocument 3)保存XDocumen的内容