Wednesday, July 21, 2010



LINQ let us to read from varied data-store, xml is one of them. Let’s find out how we can read from an xml file using LINQ.Using LINQ with xml is often referred as XLINQ.
Here we need an xml file we add one into our web-project under XML folder call it Movie.xml
Inside this file I am adding a simple xml data,simple in sense that we don’t have an attributes with this tags.

XML file:

<?xml version="1.0" encoding="utf-8" ?>
<Director>Farahan Akhtar</Director>
<Genere>Love Story</Genere>
<Director>Sanket Pawar</Director>
<Genere>Love Story</Genere>
<Director>Karan Johar</Director>
<Genere>Love Story</Genere>
<Director>Rakesh Roshan</Director>
<Genere>Love Story</Genere>

Now we have this xml file,we add a gridview to our page say gridview1.
In page load of this page add

Page_load code:
var query = from m in XElement.Load(MapPath("XML/Movie.xml")).Elements("Movie")
select new Movie { Title = (string)m.Element("Title"),
Director = (string)m.Element("Director"),
Genere = (string)m.Element("Genere"),
Rating = (int)m.Element("Rating"),
ReelSize = (int)m.Element("ReelSize"),
ReleaseOn = (DateTime)m.Element("ReleaseOn")
this.GridView1.DataSource = query;

Here we need to have Movie class else we will not compiler hurdle.
Lets have in same namespace

Movie class code:

public class Movie
public string Title { get; set; }
public string Director { get; set; }
public string Genere { get; set; }
public int Rating { get; set; }
public int ReelSize { get; set; }
public DateTime ReleaseOn { get; set; }

Nothing great is done just we added properties to map elemnet in our xml.

Run the code to find that datagrid is populated as required.

In next article we will go for more complex xml.

No comments:

Post a Comment