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

I use this C # code to write data to an 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 existing data, using the same method that overwrites the data in my XML file, I tried to figure out how to do this, and I looked for a similar example. but I could not come to anything, any ideas?

+4
source share
2 answers

Perhaps you should take a 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 if you do not have the number of entries.

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

xml- . XDocument, , .

XDocument, XML XElement XAttribute, , .

+1

All Articles