C# .NET - Help for this issue - Asked By Srinivasan S on 17-Nov-11 08:07 AM

How can i append existing XML data with the new data in c#?

Code USed for write:

datatable dt=new datatable();
datarow dr;

dr = dt.NewRow();


"Name"] = txtName.Text;

dr["Age"] = txtAge.Text;




code used for read:


dataGridView1.DataSource = ds.Tables[0];

Kirtan Patel replied to Srinivasan S on 17-Nov-11 08:21 AM
XML files are TextFile With Sequential nature so every time you need to append some data you need to overwrite the existing file to add new data .
To Append data
Step 1 : Read the file from XML to dataTable
Step 2 : Add New Row
Step 3: Write the data you want
Step 4 : Overwrite the File Previously Saved !
Step 5 : Done
Reena Jain replied to Srinivasan S on 17-Nov-11 09:35 AM

You can't append an XML file - you'll have to load the file in memory , modify/add/etc, and then write it to disk.


Well, for loading a file you would use :

XmlDocument xmlDoc= new XmlDocument(); // create an xml document object.
.Load("yourXMLFile.xml");// load from file
// create the structure of your xml document
XmlElement root = xmlDoc.CreateElement("STATS");

and then start adding the keepalive stuff.

I would actually go a bit further and not mess around with xml. I'd create a class that contains everything I need and just serialize and deserialize it.

Here's an example of adding a new element to the root node:

XDocument doc = XDocument.Load("test.xml");
.Root.Add(new XElement("someNode", "some node value"));