我有这个xml文件
<?xml version="1.0" encoding="utf-8"?>
<Root>
<Day id="Monday">
<subject name="Software Testing" session="2010" group="Alpha" teacher="Tasawar Khan" classroom="Class Room 1" time="8:30">
</subject>
</Day>
<Day id="Tuesday">
<subject name="Digital Image Processing" session="2011" group="Alpha" teacher="Ali Javed" classroom="Class Room 2" time="11:30">
</subject>
</Day>
<Day id="Wednesday">
<subject name="Digital Image Processing" session="2011" group="Alpha" teacher="Ali Javed" classroom="Class Room 2" time="11:30">
</subject>
</Day>
<Day id="Thursday">
<subject name="Digital Image Processing" session="2011" group="Alpha" teacher="Ali Javed" classroom="Class Room 2" time="11:30">
</subject>
</Day>
<Day id="Friday">
<subject name="Digital Image Processing" session="2011" group="Alpha" teacher="Ali Javed" classroom="Class Room 2" time="11:30">
</subject>
</Day>
</Root>
我想根据Id添加内部元素中的主题元素。 我已经为它编写了这段代码。
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();
XDocument loadedData = XDocument.Load(TeachersXMLPath);
var newElement = new XElement("subject", new XAttribute("name", subject),
new XAttribute("session", session),
new XAttribute("group", "alpha"),
new XAttribute("teacher", teacher),
new XAttribute("classroom", classroom),
new XAttribute("time", time));
isoStream.Position = 0;
loadedData.Root.Add(newElement);
loadedData.Save(isoStream);
}
现在我面临两个问题。
答案 0 :(得分:0)
尝试将FileMode
更改为Create
而不是Open
,因为您的代码会将所有现有文件加载到XDocument
并将整个XDocument
写回隔离存储最后。
要在正确的<Subject>
代码下添加新的<Day>
,您需要先选择<Day>
代码。有几种可能的方法,例如:
var day = loadedData.Root.Element("Day")
.FirstOrDefault(o => (string)o.Attribute("id") == "Thursday");
day.Add(newElement);
loadedData.Save(isoStream);