Windows Phoneで既存のXMLファイルを更新する
-
22-12-2019 - |
質問
Windows PhoneでデータをXMLファイルに保存するには、以下のコードを使用しています。まず、ターゲットXMLファイルが絶縁ストレージに存在するかどうかを確認しています。 存在しない場合は、ファイルを作成して必要な要素データを追加しています。ファイルが存在する場合は、最初に要素が既に存在するかどうかを確認している場合は、属性値を更新しています。それ以外の場合は、XMLファイルに新しい要素を追加します。
すでに要素が存在していて属性を更新しようとしている問題は、新しいデータを追加した追加の要素を見てファイルに古いデータが存在しています。代わりに更新されていません。
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