Farhad Jabiyev
Farhad Jabiyev

Reputation: 26655

How to append node to xml file in Silverlight?

I have a xml file in ClientBin folder with the name XMLFile1.xml. There are three nodes in file:

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

I can read nodes from file like that:

   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;
            }
        }

But i cant append node to this. What i have done yet with XDocument and XMLDocument gave me compile errors. Thanks.

Update : For example I have tried something like that:

string FirstName = "Ferhad"; string 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);

Upvotes: 1

Views: 360

Answers (1)

Jon Skeet
Jon Skeet

Reputation: 1502376

This is the problem:

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

Two issues:

  • That tries to add to the root of the document. There's already a root element, so that will fail.
  • That's trying to add a Personto the document. You want to add an XElement.

So you probably want:

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

Upvotes: 1

Related Questions