我在Windows Phone 8.0 Silverlight中更新XML文件中的内容时遇到问题。我尝试了这个代码,应用程序运行没有任何错误,但XML没有改变任何东西。 这是我的C#代码
public static void WriteUserData(string filePath, User userObj)
{
StreamResourceInfo stream = Application.GetResourceStream(new Uri(filePath, UriKind.RelativeOrAbsolute));
stream.Stream.Position = 0;
XDocument doc = XDocument.Load(stream.Stream);
foreach (var itemU in doc.Descendants("user"))
foreach (var itemP in itemU.Descendants("player"))
{
itemP.SetElementValue("name", "12332");
itemP.SetElementValue("high", "12332");
itemP.SetElementValue("current", "12332");
itemP.SetElementValue("played", "12332");
}
}
这些是我的XML文件中的内容。
<?xml version="1.0" encoding="utf-8" ?>
<user>
<player>
<name>123123</name>
<high>181</high>
<current>0</current>
<played>0</played>
</player>
</user>
调试程序贯穿所有行,但事情没有发生,请帮助我!
答案 0 :(得分:1)
要在Windows手机上更新XML文件,您必须使用独立存储。
IsolatedStorageFile file = IsolatedStorageFile.GetUserStoreForApplication();
string fileName = "YourFileName.xml";
XDocument document;
if (file.FileExists(fileName))
using (IsolatedStorageFileStream stream = file.OpenFile(fileName, System.IO.FileMode.Open))
{
document = XDocument.Load(stream);
}
else
document = XDocument.Load(fileName);
var root = new XElement("player");
var name = new XElement("name", "1233");
var high = new XElement("high", "1233");
var current = new XElement("current ", "1233");
var played = new XElement("played ", "1233");
root.Add(name, high, current,played);
document.Root.Add(root);
using (IsolatedStorageFileStream stream = file.CreateFile(fileName))
{
document.Save(stream);
}