Using LINQ to Add Data to XML File


Using LINQ to XML to Add Data to XML File :
This post is all about how to write values to an XML.

Linq to XML is the modern approach to programming with XML
XDocument class and XElement class (3.5 or HigherVersion) in System.Xml.Linq can be used to do this easily.

Members of this class library are:


XDocument :
– Represents an XML document.


XElement :
– Represents an XML element.

CodeSnippet given below shows how to do it.

CodeSnippet:


using System;
using System.Collections.Generic;
using System.Linq;
using System.IO;
using System.Web;
using System.Xml;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Xml.Linq;

public partial class _Default : System.Web.UI.Page 
{
    protected void Page_Load(object sender, EventArgs e)
    {
        var Document = new XDocument();

        var PersonalData = new XElement("ComPanyDetails");

        ComPanyDetails.Add(new XElement("CompanyName", "Nexgen"));
        ComPanyDetails.Add(new XElement("Location", "White Plains"));

        Document.Add(ComPanyDetails);
        String Maindirectory = Server.MapPath("~");
        Directory.CreateDirectory(Maindirectory + "\\XmlFolder");
        Document.Save(Maindirectory + "\\XmlFolder"+ "\\PD.xml");
    
    }
}


Explanation:

This code first creates a new XDocument.the code then creates a new XElement that will be the root node of the XML string. here in our code, the root node is “ComPanyDetails”

The sub elements are then added to the root element. In this case, the sub elements are “CompanyName”, “Location”, and the values of the elements are manualy entered .

We then created a Folder “XmlFolder” in the the application Folder.The XML is saved in the this Folder
Check my Previous post on Saving and Reading the image
Click here

Happy Coding! 😉

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: