在xml中添加新元素

时间:2014-04-15 07:32:24

标签: xml windows-phone-8 xml-attribute

我有这个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);
}

现在我面临两个问题。

  • 此代码没有错误,但是当我打开xml文件时,根本没有添加任何数据。
  • 第二个代码,即使工作(不是)。它会在里面的数据。我怎么能用特定的id添加它。

1 个答案:

答案 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);