What is the LINQ To XML ?
It is the type of LINQ. Using Linq we can perform all basic operation with XML file.
I will show one of the easiest example
Step1: Create one XML file in asp.net project like this
<?xml version=”1.0″ encoding=”utf-8″ ?>
<movies>
<movie>
<Title>Ghost </Title>
<Director>ABC</Director>
</movie>
<movie>
<Title>Forest </Title>
<Director>CDE</Director>
</movie>
<movie>
<Title>Water </Title>
<Director>EEE</Director>
</movie>
<movie>
<Title>Salt</Title>
<Director>WWW</Director>
</movie>
</movies>
Step2: Go to Solution Explorer, Right click on it and add a class “Movie.cs” .
You declare the property like this
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;/// <summary>
/// Summary description for Movie
/// </summary>
public class Movie
{public string Title { get; set; }
public string Director { get; set; }}
Step3: Take one gridview Control in design page
Step4: Add a namespace
using System.Xml.Linq;
Step5: Write the code in code behind page like this
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
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 query = from a in
// XElement.Load(MapPath(“Movie.xml”)).Elements(“movie”)
// select a;
var query = from a in
XElement.Load(MapPath(“Movie.xml”)).Elements(“movie”)
select new Movie
{
Title = (string)a.Element(“Title”),
Director = (string)a.Element(“Director”)
};
GridView1.DataSource = query;
GridView1.DataBind();
}
}
Step6:You will get op like this
Dear Sir,
I am writing this code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Xml.Linq;
namespace xml2linq
{
public partial class About : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
var query = from a in
XElement.Load(MapPath(“Movie.xml”)).Elements(“movie”)
select new Movie
{
Title = (string)a.Element(“Title”),
Director = (string)a.Element(“Director”)
};
GridView1.DataSource = query;
GridView1.DataBind();
}
}
}
And I’m getting error for “select new Movie”
Error 1 The type or namespace name ‘Movie’ could not be found (are you missing a using directive or an assembly reference?) c:\users\beky\documents\visual studio 2010\Projects\xml2linq\xml2linq\About.aspx.cs 18 24 xml2linq
Thank you in advance…
Dear friend
Thanks for sending the comment.Actually “Movie” class was not there so it was giving the error. Now you add a class i.e Movie and declare the property.It will work.I have updated in my post. If you are getting any errors, Let me inform.