SIGN UP MEMBER LOGIN:    
ARTICLE

Inserting Data to an XML Document

Posted by Mahesh Chand Articles | XML in C# March 28, 2001
The XmlNode and the XmlDocument classes can be used to insert XML data to an existing document or to a new document.
Reader Level:

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:  

try
{
XmlNode currNode;
XmlDocument doc =
new XmlDocument();
doc.LoadXml("<XMLFile>"+" <SomeData>Old Data</SomeData>" +"</XMLFile>");
XmlDocumentFragment docFrag = doc.CreateDocumentFragment();
docFrag.InnerXml="
<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
doc.Save("InsertedDoc.xml");
}
catch (Exception e)
{
Console.WriteLine ("Exception: {0}", e.ToString());
}

output of the code looks like this -

<XMLFile>
<SomeData>
Old Data
<Inserted>
<NewData>Inserted Data</NewData>
</Inserted>
</SomeData>
</XMLFile>

Login to add your contents and source code to this article
share this article :
post comment
 
Nevron Gauge for SharePoint
Become a Sponsor
PREMIUM SPONSORS
  • Get 2 Months Free of ASP.NET Hosting for Only $4.95/month! Receive FREE MS SQL and MySQL Databases Including ASP.NET 4/3.5, MVC 3.0, Silverlight 4, Windows 2008/IIS 7.0 Plus FREE IIS 7 Modules. Host UNLIMITED ASP.NET Web Sites - Click Here!
    ceTE software specializes in components for dynamic PDF generation and manipulation. The DynamicPDF™ product line allows you to dynamically generate PDF documents, merge PDF documents and new content to existing PDF documents from within your applications. Visit DynamicPDF here
Become a Sponsor