Taha
Taha

Reputation: 2306

How to add data to an existing xml file in c#

I'm using this c# code to write data to xml file:

Employee[] employees = new Employee[2];
employees[0] = new Employee(1, "David", "Smith", 10000);
employees[1] = new Employee(12, "Cecil", "Walker", 120000);

using (XmlWriter writer = XmlWriter.Create("employees.xml"))
{
    writer.WriteStartDocument();
    writer.WriteStartElement("Employees");

    foreach (Employee employee in employees)
    {
    writer.WriteStartElement("Employee");

    writer.WriteElementString("ID", employee.Id.ToString());
    writer.WriteElementString("FirstName", employee.FirstName);
    writer.WriteElementString("LastName", employee.LastName);
    writer.WriteElementString("Salary", employee.Salary.ToString());

    writer.WriteEndElement();
    }

    writer.WriteEndElement();
    writer.WriteEndDocument();
}

Now suppose I restart my application and I want to add new data to the xml file without losing the existed data, using the same way will overwrite the data on my xml file, I tried to figure out how to do that and I searched for a similar example but I couldn't come to anything , any ideas ??

Upvotes: 4

Views: 24633

Answers (2)

Ceelie
Ceelie

Reputation: 241

Perhaps you should look at some examples using datasets and xml:

http://www.codeproject.com/Articles/13854/Using-XML-as-Database-with-Dataset

or use System.Xml.Serialization.XmlSerializer, when you dont't have amount of records.

Example using XmlDocument

XmlDocument xd = new XmlDocument();
xd.Load("employees.xml");
XmlNode nl = xd.SelectSingleNode("//Employees");
XmlDocument xd2 = new XmlDocument();
xd2.LoadXml("<Employee><ID>20</ID><FirstName>Clair</FirstName><LastName>Doner</LastName><Salary>13000</Salary></Employee>");
XmlNode n = xd.ImportNode(xd2.FirstChild,true);
nl.AppendChild(n);
xd.Save(Console.Out);

Upvotes: 6

Anders Abel
Anders Abel

Reputation: 69250

Using an xml writer for small amounts of data is awkward. You would be better of using an XDocument that you either initialize from scratch for the first run, or read from an existing file in subsequent runs.

Using XDocument you can manipulate the XML with XElement and XAttribute instances and then write the entire thing out to a file when you want to persist it.

Upvotes: 1

Related Questions