C# .NET - XML append data - Asked By Srinivasan S on 17-Nov-11 08:41 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];

Help me in this code...
Kirtan Patel replied to Srinivasan S on 17-Nov-11 08:46 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
Suchit shah replied to Srinivasan S on 17-Nov-11 08:49 AM
You should use the XmlDocument class to load the whole file, modify it in memory and then write the contents back replacing the original file. Don't worry, it won't mess up your markup, and you can even ask it to preserve non-significant whitespace in the original document using the PreserveWhitespaceproperty (http://msdn.microsoft.com/en-us/library/system.xml.xmldocument.preservewhitespace.aspx).
private void btnCreateXMLDoc_Click(object sender, EventArgs e)

{AddBook(txtISBN.Text, txtBookName.Text, txtPublication.Text, txtPublishYear.Text);}
private void AddBook(string ISBN, string Title, string Publisher, string PublishYear)
{ XmlElement booksElement = null ;
if (!File.Exists(sStartupPath + @"\Books.xml"))
if (booksElement == null)
booksElement = xmlDoc.CreateElement("Books");
xmlDoc.Save(sStartupPath + @"\Books.xml");
xmlDoc.Load(sStartupPath + @"\Books.xml");
booksElement = xmlDoc.DocumentElement; //getting the root element name
XmlElement bookElement = xmlDoc.CreateElement("Book");
//Attributes are extra information added to a node element itself
XmlAttribute bookAttribute = xmlDoc.CreateAttribute("ISBN");
bookAttribute.Value = ISBN.Trim();

XmlElement titleElement = xmlDoc.CreateElement("Title");
titleElement.InnerText = Title.Trim();

XmlElement releaseElement = xmlDoc.CreateElement("Release");
releaseElement.InnerText = PublishYear.Trim();
XmlElement publisherElement = xmlDoc.CreateElement("Publisher");
publisherElement.InnerText = Publisher.Trim();
xmlDoc.Save(sStartupPath + @"\Books.xml");