Linq to XML & ASP.Net - part 7


This is the seventh post in a new series of posts regarding LINQ to XML and ASP.Net.Please do read the first post here. You can find the second post here .

You can find the third post here . You can read the fourth post here . You can find the fifth post here . You can find the sixth post here .

In this post I would like to show on how to add new elements at runtime using Linq to XML.

I will use Visual Studio 2010 Ultimate edition and C# as the development language. Visual Studio 2010/2008 express editions will suffice.  


1) Fire VS and create a web site. Choose an appropriate name for your site.

2) In the code behind file Default.aspx.cs, add the namespace

using System.Xml.Linq;

All the classes we need to manipulate XML documents are inside this namespace.

 

Add the existing students.xml file in your website. You can find this file in the first post.

3) In the Page_Load  event handling routine of the default.aspx.cs file, type the following

 XElement xelement = XElement.Load(@"C:\Users\fofo\Documents\
Visual Studio 2010\WebSites\forblog\xml\students.xml");

     xelement.Add(new XElement("Student",
     new XElement("StudenId", 5),
     new XElement("Name""Emily"),
     new XElement("Sex""Female"),
     new XElement("Seminar","ASP.NET"new XAttribute("Type","E-Learning")),
     new XElement("Seminar","WPF"new XAttribute("Type","Blended Learning"))
        
     ));

        Response.Write(xelement);

 

4) You can add a new Element to an XML document at runtime by using the Add() method of XElement.

The new element gets added as the last element of the XML document.If you want to add the Element as the First Child, use the AddFirst() method.

5) Run your application and see in the browser the new item added.

Email me if you need the source code.

Hope it helps!!!

No Comments