0

我有一个这样的 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>
4

1 回答 1

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");
}
于 2014-04-22T18:26:06.077 回答