我在 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);