Search This Blog

2010/07/21

XLINQ:

XLINQ:

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" ?>
<Movies>
<Movie>
<Title>DCH</Title>
<Director>Farahan Akhtar</Director>
<Genere>Love Story</Genere>
<Rating>3</Rating>
<ReleaseOn>2008-02-03</ReleaseOn>
<ReelSize>2</ReelSize>
</Movie>
<Movie>
<Title>RHTDM</Title>
<Director>Sanket Pawar</Director>
<Genere>Love Story</Genere>
<Rating>3</Rating>
<ReleaseOn>2009-04-06</ReleaseOn>
<ReelSize>3</ReelSize>
</Movie>
<Movie>
<Title>K3G</Title>
<Director>Karan Johar</Director>
<Genere>Love Story</Genere>
<Rating>3</Rating>
<ReleaseOn>2010-11-16</ReleaseOn>
<ReelSize>3</ReelSize>
</Movie>
<Movie>
<Title>Kites</Title>
<Director>Rakesh Roshan</Director>
<Genere>Love Story</Genere>
<Rating>2</Rating>
<ReleaseOn>2008-10-11</ReleaseOn>
<ReelSize>2</ReelSize>
</Movie>
</Movies>

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;
this.GridView1.DataBind();

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