Bharat Bharat - 3 years ago 125
ASP.NET (C#) Question

gridview with xml datasource

I am new to asp.net web forms.

I have XML, like below.

<table>
<row id="1" name="name1"/>
<row id="2" name="name2"/>
<row id="3" name="name3"/>
<row id="4" name="name3"/>
<row id="5" name="name3"/>
</table>


I want to bind this data to asp:GridView.
But only name part of xml not Id.

What I did is here, but it's not all.
I don't even know that it's proper or not.

protected void Page_Load(object sender, EventArgs e)
{
var XmlPath = Server.MapPath("~/Data.xml");
XmlDocument doc = new XmlDocument();
doc.Load(XmlPath);

DataTable dt = new DataTable();
foreach (XmlNode xn in doc.ChildNodes[1])
{
string tagName = xn.Name;
if (!dt.Columns.Contains(tagName))
{
dt.Columns.Add(tagName);
}

}
DataRow dr = dt.NewRow();
foreach (XmlNode xn in doc.ChildNodes[1])
{
dr[xn.Name] = xn.InnerText;
}

dt.Rows.Add(dr);

GridView1.DataSource = dt;
GridView1.DataBind();
}



I also have to filter data, for exa. I want to print only those data whose ID is 2 and 4.

Answer Source

You can use LINQ to XML like this:

XDocument doc = XDocument.Load("~/Data.xml");

var names = from r in doc.Descendants("row")
             select (string)r.Attribute("name");

GridView1.DataSource = names;
GridView1.DataBind();
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download