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