Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

xml

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 ??

like image 547
T-D Avatar asked Feb 14 '23 17:02

T-D


2 Answers

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);
like image 76
Ceelie Avatar answered Feb 17 '23 08:02

Ceelie


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.

like image 27
Anders Abel Avatar answered Feb 17 '23 06:02

Anders Abel