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

dr[

"Name"] = txtName.Text;

dr["Age"] = txtAge.Text;

dt.Rows.Add(dr);


ds.Tables.Add(dt);


ds.WriteXml(filepath);

code used for read:

ds.ReadXml(filepath);

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
Hi,

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.

EDIT :

Well, for loading a file you would use :

XmlDocument xmlDoc= new XmlDocument(); // create an xml document object.
if(System.IO.File.Exists("yourXMLFile.xml")
    xmlDoc
.Load("yourXMLFile.xml");// load from file
else{
   
// create the structure of your xml document
   
XmlElement root = xmlDoc.CreateElement("STATS");
   xmlDoc
.AppendChild(root);
}

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");
doc
.Root.Add(new XElement("someNode", "some node value"));
doc
.Save("test.xml");