Tuesday, August 10, 2010

Linq to XML

Here we are just going to see how we can associate XML with LinQ.

First create an XML file with the structure like this CLICK HERE

Now add a GridView to your design.

We need

System.Xml.Linq;

namespace for working of XLINQ

Now in the page load event add the code like this..
------------------------------------------------------
var query = from s in XElement.Load(MapPath("Students.xml")).Elements("Student1")
select new
{
Name = (string)s.Element("StName"),
Address = (string)s.Element("StAddress"),
PhNo = (string)s.Element("StPHNO"),
flag = (int)s.Element("Flag")
};

GridView1.DataSource=query;
GridView1.DataBind();
------------------------------------------------------
In the above code we are using XElement.Load method to Load the Students.xml file and we must mention the Node inside which we have put the informations.

(string)s.Element("StName")
The above method converts the data inside the Node to the type we have specified and stores into it....
When we execute it we will get a GridView which contains columns Name, Address, PhNo, and Flag..


No comments: