更新wp7中的XML XNode值

时间:2012-12-30 10:11:05

标签: c# linq-to-xml isolatedstorage

你好朋友我需要一些关于在wp7中更新xml节点的帮助。我的xml如下:

<?xml version="1.0" encoding="utf-8"?>
<ConfigData>
  <CallerNo1>123</CallerNo1>
  <MobileNo1>123</MobileNo1>
  <MobileNo2>123</MobileNo2>
  <MobileNo3>123</MobileNo3>
  <MobileNo4>123</MobileNo4>
  <MobileNo5>123</MobileNo5>
  <EmailNo1>123</EmailNo1>
  <EmailNo2>123</EmailNo2>
  <EmailNo3>123</EmailNo3>
  <EmailNo4>123</EmailNo4>
  <EmailNo5>123</EmailNo5>
</ConfigData> 

我想将值更新为1111,所以我编写了以下代码来实现它:

using (IsolatedStorageFile myIsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication())
                {
                    IsolatedStorageFileStream isoFileStream = myIsolatedStorage.OpenFile("Configuration.xml", FileMode.Open, FileAccess.ReadWrite);
                    XDocument xml = XDocument.Load(isoFileStream, LoadOptions.None);
                    xml.Element("ConfigData").SetElementValue("CallerNo1", "11111");
                    xml.Save(isoFileStream);
                    isoFileStream.Flush();
                    isoFileStream.Close();
                }

然后我再次读取文件后显示xml如下:

<?xml version="1.0" encoding="utf-8"?>
<ConfigData>
  <CallerNo1>123</CallerNo1>
  <MobileNo1>123</MobileNo1>
  <MobileNo2>123</MobileNo2>
  <MobileNo3>123</MobileNo3>
  <MobileNo4>123</MobileNo4>
  <MobileNo5>123</MobileNo5>
  <EmailNo1>123</EmailNo1>
  <EmailNo2>123</EmailNo2>
  <EmailNo3>123</EmailNo3>
  <EmailNo4>123</EmailNo4>
  <EmailNo5>123</EmailNo5>
</ConfigData><?xml version="1.0" encoding="utf-8"?>
<ConfigData>
  <CallerNo1>11111</CallerNo1>
  <MobileNo1>123</MobileNo1>
  <MobileNo2>123</MobileNo2>
  <MobileNo3>123</MobileNo3>
  <MobileNo4>123</MobileNo4>
  <MobileNo5>123</MobileNo5>
  <EmailNo1>123</EmailNo1>
  <EmailNo2>123</EmailNo2>
  <EmailNo3>123</EmailNo3>
  <EmailNo4>123</EmailNo4>
  <EmailNo5>123</EmailNo5>
</ConfigData>

创建新的xml并将其附加到现有的xml,应该怎么做才能更改xml文件?

1 个答案:

答案 0 :(得分:1)

这是因为当您在Save(Stream)实例上调用XmlDocument时,您正在写入isoFileStream的末尾,您需要重置流中的位置以写入已经存在的内容那里。

最简单的方法是创建一个新的IsolatedStorageFileStream进行编写:

using (IsolatedStorageFile myIsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication())
{
    XDocument xml = null;
    //Read the file stream into an XDocument using a reading stream
    using (IsolatedStorageFileStream isoFileStream = myIsolatedStorage.OpenFile("Configuration.xml", FileMode.Open, FileAccess.Read))
    {
        xml = XDocument.Load(isoFileStream, LoadOptions.None);
        xml.Element("ConfigData").SetElementValue("CallerNo1", "11111");
    }

    //Write it back out using a write one.
    using (IsolatedStorageFileStream isoFileStream = myIsolatedStorage.OpenFile("Configuration.xml", FileMode.Truncate, FileAccess.Write))
    {
        xml.Save(isoFileStream, SaveOptions.None);
    }
 }