4

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

2
  • 1
    A simple way would be to read the file into memory, modify it there, and overwrite the file. Commented Nov 10, 2013 at 20:20
  • 1
    Check out this answer stackoverflow.com/questions/9188574/… Commented Nov 10, 2013 at 20:21

2 Answers 2

6

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);
Sign up to request clarification or add additional context in comments.

1 Comment

using the code above and replacing the last line xd.Save("employees.xml"); is what I was looking for, thanks.
1

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.

1 Comment

Is there any example ? I'm not sure how deal with this,for example can I load the xml file using XDocument then append new element using XElement ?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.