在XML中添加新元素时复制的所有元素

时间:2014-04-22 05:14:49

标签: c# xml windows-phone-8 isolatedstorage isolatedstoragefile

我有一个像这样的XML文件

<?xml version="1.0" encoding="utf-8"?>
<Root>
  <Teachers>
    <Teacher>Ali Javed</Teacher>
  </Teachers>
</Root>

我正在动态添加新元素。

using (IsolatedStorageFileStream isoStream = new IsolatedStorageFileStream(TeachersXMLPath, FileMode.Open, IsolatedStorageFile.GetUserStoreForApplication()))
{
    string session = tb_session.Text.ToString();
    string subject = tb_subject.Text.ToString();
    DateTime? _datetime = val_timer.Value;
    String time = _datetime.Value.Hour + ":" + _datetime.Value.Minute;
    string crdthr = ((ListPickerItem)lst_credithr.SelectedItem).Content.ToString();
    string teacher = tb_teacher.Text.ToString();
    string classroom = tb_class.Text.ToString();
    string day_week = tb_day.Text.ToString();
    XDocument loadedData = XDocument.Load(isoStream);

    var tchElement = new XElement("Teacher");
    var tchr = loadedData.Root.Element("Teachers");
    tchr.Add(tchElement);
    tchElement.Value = teacher;
    loadedData.Save(isoStream);
    MessageBox.Show("Added");

}

但不是添加它添加的元素,而是复制所有这样的元素。

 <?xml version="1.0" encoding="utf-8"?>
        <Root>
          <Teachers>
            <Teacher>teacher 1</Teacher>
          </Teachers>
    </Root>
<?xml version="1.0" encoding="utf-8"?>
        <Root>
          <Teachers>
            <Teacher>teacher 1</Teacher>
    <Teacher>teacher 2</Teacher>
          </Teachers>
    </Root>

1 个答案:

答案 0 :(得分:0)

看起来这里发生的事情是您使用FileMode.Open打开流,读取到流的末尾以读取XML文档,然后从该点开始写入该流。这就是你遇到这种重复的原因。

我建议将该文件作为一个访问权限读取,然后使用FileMode.Create重新打开该文件,以便完全覆盖该文件:

IsolatedStorageFile storageFile = IsolatedStorageFile.GetUserStoreForApplication();
XDocument loadedData;
using (IsolatedStorageFileStream isoStream = 
    new IsolatedStorageFileStream(TeachersXMLPath, FileMode.Open, storageFile))
{
    loadedData = XDocument.Load(isoStream);
}
using (IsolatedStorageFileStream isoStream = 
    new IsolatedStorageFileStream(TeachersXMLPath, FileMode.Create, storageFile))
{
    string session = tb_session.Text.ToString();
    string subject = tb_subject.Text.ToString();
    DateTime? _datetime = val_timer.Value;
    String time = _datetime.Value.Hour + ":" + _datetime.Value.Minute;
    string crdthr = ((ListPickerItem)lst_credithr.SelectedItem).Content.ToString();
    string teacher = tb_teacher.Text.ToString();
    string classroom = tb_class.Text.ToString();
    string day_week = tb_day.Text.ToString();

    var tchElement = new XElement("Teacher");
    var tchr = loadedData.Root.Element("Teachers");
    tchr.Add(tchElement);
    tchElement.Value = teacher;
    loadedData.Save(isoStream);
    MessageBox.Show("Added");
}