在Windows Phone中更新现有XML文件
-
22-12-2019 - |
题
我正在使用以下代码,将数据保存到Windows手机中的XML文件。首先我正在检查孤立的存储中是否存在目标XML文件; 如果它不存在,我正在创建文件并添加所需的元素数据。如果存在文件,请首先检查元素是否已存在,如果是,请在更新属性值,否则将新元素添加到XML文件。
问题是我看到的问题是,如果已有元素存在并尝试更新属性(w / delest代码) - 我会看到添加的额外元素添加,旧数据仍然存在于文件中。它没有更新而不是附加。
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);
}
. 不隶属于 StackOverflow