2012-12-04 101 views
1

我在名爲XMLFile1.xml的ClientBin文件夾中有一個xml文件。 有文件三個節點:如何將節點追加到Silverlight中的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完成了編譯錯誤。謝謝。

更新:比如我已經試過這樣的事情:

字符串名字= 「Ferhad」; string姓氏=「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); 
+0

我已經更新的問題。 –

回答

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))); 
+0

但它給我編譯加載和保存方法中的錯誤。 –

+1

@FarhadJabiyev:啊,是的 - 你試圖直接使用文件。你不能在Silverlight中做到這一點,但這與XML無關。閱讀Silverlight存儲。接下來,請閱讀http://tinyurl.com/so-list - 您應該*從不*發佈包含錯誤的編譯錯誤問題。 –

+0

好的。我知道了。謝謝。 –