Inserting Data to an XML Document

The XmlNode and the XmlDocument classes can be used to insert XML data to an existing document or to a new document.

Adding namspace Reference

Since Xml classes are defined in the System.XML namespace, so first thing you need to do is to Add the System.XML reference to the project.

using System.Xml;

Loading XML to Document

LoadXml method of XmlDocument can be used to load XML data to a document or to load an existing XML document..

// Load XML data to a document
XmlDocument doc = new XmlDocument();
doc.LoadXml("<XMLFile>" +" <SomeData>Old Data</SomeData>" + "</XMLFile>");

Inserting XML Data

The below code inserts XML data to the file and saves file as InsertedDoc.xml.

Souce Code:  

XmlNode currNode;
XmlDocument doc =
new XmlDocument();
doc.LoadXml("<XMLFile>"+" <SomeData>Old Data</SomeData>" +"</XMLFile>");
XmlDocumentFragment docFrag = doc.CreateDocumentFragment();
<Inserted>"+"<NewData>Inserted Data</NewData>"+"</Inserted>";
// insert the availability node into the document
currNode = doc.DocumentElement.FirstChild;
currNode.InsertAfter(docFrag, currNode.LastChild);
//save the output to a file
catch (Exception e)
Console.WriteLine ("Exception: {0}", e.ToString());

output of the code looks like this -

Old Data
<NewData>Inserted Data</NewData>

Similar Articles
Founded in 2003, Mindcracker is the authority in custom software development and innovation. We put best practices into action. We deliver solutions based on consumer and industry analysis.