如何将节点附加到Silverlight中的xml文件?

时间:2012-12-04 11:57:11

标签: c# xml silverlight

我在ClientBin文件夹中有一个名为XMLFile1.xml的xml文件。 文件中有三个节点:

<?xml version="1.0" encoding="utf-8" ?>
<People>
  <Person FirstName="Ram" LastName="Sita"/>
  <Person FirstName="Krishna" LastName="Radha"/>
  <Person FirstName="Heer" LastName="Ranjha"/>
</People>

我可以从文件中读取节点:

   public class Person
        {
            public string FirstName { get; set; }
            public string LastName { get; set; }
        }



private void Button_Click_1(object sender, RoutedEventArgs e)
{

    Uri filePath = new Uri("XMLFile1.xml", UriKind.Relative);
    WebClient client1 = new WebClient();
    client1.DownloadStringCompleted += new DownloadStringCompletedEventHandler(client1_DownloadStringCompleted);

    client1.DownloadStringAsync(filePath);
}


  void client1_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
        {
            if (e.Error == null)
            {
                XDocument doc = XDocument.Parse(e.Result);
                IEnumerable<Person> list = from p in doc.Descendants("Person")
                                           select new Person
                                           {
                                               FirstName = (string)p.Attribute("FirstName"),
                                               LastName = (string)p.Attribute("LastName")
                                           };
                DataGrid1.ItemsSource = list;
            }
        }

但是我无法将节点添加到此处。我用XDocument和XMLDocument做了什么给了我编译错误。感谢。

更新:例如,我尝试过类似的内容:

string FirstName =&#34; Ferhad&#34 ;;         string LastName =&#34; Cebiyev&#34 ;;

    XDocument xmlDoc = new XDocument();
    string path = "C:\\Users\\User\Desktop\\temp\\SilverlightApplication3\\SilverlightApplication3.Web\\ClientBin\\XMLFile1.xml";
    xmlDoc.Load(path);
    xmlDoc.Add(new Person { FirstName=FirstName, LastName = LastName});

    xmlDoc.Save(path);

1 个答案:

答案 0 :(得分:1)

这是问题所在:

xmlDoc.Add(new Person { FirstName=FirstName, LastName = LastName});

两个问题:

  • 尝试添加到文档的 root 。已经存在根元素,因此会失败。
  • 那是尝试在文档中添加Person。您想添加XElement

所以你可能想要:

xmlDoc.Root.Add(new XElement("Person",
                             new XAttribute("FirstName", FirstName),
                             new XAttribute("LastName", LastName)));