C# 在Windows Phone中更新现有xml文件
我使用下面的代码将数据保存到Windows Phone中的xml文件中。首先我检查目标xml文件是否存在于隔离存储中; 如果它不存在,我将创建该文件并添加所需的元素数据。如果文件存在,首先检查元素是否已经存在,如果已经存在,则更新属性值,否则将向xml文件添加新元素 我看到的问题是,如果元素已经存在并试图更新属性(下面的代码)-我看到额外的元素添加了新数据,而旧数据仍然存在于文件中。它不是更新,而是追加C# 在Windows Phone中更新现有xml文件,c#,xml,windows-phone-8,isolatedstoragefile,C#,Xml,Windows Phone 8,Isolatedstoragefile,我使用下面的代码将数据保存到Windows Phone中的xml文件中。首先我检查目标xml文件是否存在于隔离存储中; 如果它不存在,我将创建该文件并添加所需的元素数据。如果文件存在,首先检查元素是否已经存在,如果已经存在,则更新属性值,否则将向xml文件添加新元素 我看到的问题是,如果元素已经存在并试图更新属性(下面的代码)-我看到额外的元素添加了新数据,而旧数据仍然存在于文件中。它不是更新,而是追加 using (IsolatedStorageFile storage = IsolatedS
using (IsolatedStorageFile storage = IsolatedStorageFile.GetUserStoreForApplication())
{
if (storage.FileExists(fileName))
{
using (IsolatedStorageFileStream isoStream = new IsolatedStorageFileStream(fileName, FileMode.Open, storage))
{
XDocument doc = XDocument.Load(isoStream);
bool isUpdated = false;
foreach (var item in (from item in doc.Descendants("Employee")
where item.Attribute("name").Value.Equals(empName)
select item).ToList())
{
// updating existing employee data
// element already exists, need to update the existing attributes
item.Attribute("name").SetValue(empName);
item.Attribute("id").SetValue(id);
item.Attribute("timestamp").SetValue(timestamp);
isUpdated = true;
}
if (!isUpdated)
{
// adding new employee data
doc.Element("Employee").Add(
new XAttribute("name", empName),
new XAttribute("id", id),
new XAttribute("timestamp", timestamp));
}
doc.Save(isoStream);
}
}
else
{
// creating XML file and adding employee data
using (IsolatedStorageFileStream isoStream = new IsolatedStorageFileStream(fileName, FileMode.Create, storage))
{
XDocument doc = new XDocument(new XDeclaration("1.0", "utf8", "yes"),
new XElement("Employees",
new XElement("Employee",
new XAttribute("name", empName),
new XAttribute("id", id),
new XAttribute("timestamp", timestamp))));
doc.Save(isoStream, SaveOptions.None);
}
}
}
将打开的流位置设置为0或将XML文档保存在新打开的流中
XDocument doc = null;
using (IsolatedStorageFileStream isoStream = new IsolatedStorageFileStream(fileName, FileMode.Open, storage))
{
doc = XDocument.Load(isoStream);
bool isUpdated = false;
foreach (var item in (from item in doc.Descendants("Employee")
where item.Attribute("name").Value.Equals(empName)
select item).ToList())
{
// updating existing employee data
// element already exists, need to update the existing attributes
item.Attribute("name").SetValue(empName);
item.Attribute("id").SetValue(id);
item.Attribute("timestamp").SetValue(timestamp);
isUpdated = true;
}
if (!isUpdated)
{
// adding new employee data
doc.Element("Employee").Add(
new XAttribute("name", empName),
new XAttribute("id", id),
new XAttribute("timestamp", timestamp));
}
//First way
//isoStream.Position = 0;
//doc.Save(isoStream);
}
//Or second way
using (var stream = storage.OpenFile(fileName, FileMode.Open, FileAccess.Write))
{
doc.Save(stream);
}
你的代码在我看来很好…我在控制台应用程序上试过了,它按预期工作-更新现有元素并在现有文件中添加新元素。但是在WP上,它并没有像预期的那样工作。我不确定我做错了什么。谢谢Jan,将流位置重置为开始解决了问题。