1

我在 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 所做的事情给了我编译错误。谢谢。

更新:例如,我尝试过这样的事情:

字符串 FirstName = "Ferhad"; 字符串 LastName = "Cebiyev";

    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);
4

1 回答 1

1

这就是问题:

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

两个问题:

  • 这试图添加到文档的根目录。已经有一个根元素,所以这将失败。
  • 那是试图Person在文档中添加一个。您想添加一个XElement.

所以你可能想要:

xmlDoc.Root.Add(new XElement("Person",
                             new XAttribute("FirstName", FirstName),
                             new XAttribute("LastName", LastName)));
于 2012-12-04T12:04:04.457 回答