I have an XML file as follows -
The Autobiography of Benjamin Franklin
8.99
The Confidence Man
11.99
I have to display the content in the above XML in a Table/Gridview (Titles for the Table - Price|Title).
What is the best way to display the above content in a table using ASP.NET(C#)?
Sunny SharmaPosted Jul 29, 2013, 5:23 AM
I think I have the answer for your question.
As you need the code to remain unchanged even after the schema of the XML file is modified, Yes, there's a way.
Although DataTable doesn't facilitate you to read xml file, create schema and map the data to itself but DataSet does.
Now to answer your question, you can follow the sample code below to get this job done:
-------------------------------------
void BindXmlToGrid()
{
DataSet ds = new DataSet();
ds.ReadXml(@"D:\books.xml");
GridView1.DataSource = ds.Tables[0];
GridView1.DataBind();
}
----------------------------------------
As you can see, I didn't create any schema and it is mapped to the table at position 0 in dataset. So, this is the way you are seeking for. You don't need to bother about the changes in schema. Yes, do put a try catch block to check if schema is invalid and nothing is imported to DataSet.
Hope it Helps. Happy Coding :)
Cheers!
Rosi Sreenivasa ReddyPosted Jul 29, 2013, 3:37 AM
this is thank u for this answer.I am also using this answer.
in asp page what header file u use for XmlFile
Sanjeeb LenkaPosted Jul 29, 2013, 3:28 AM
Iftikar HussainPosted Jul 29, 2013, 3:13 AM
Regards,
Iftikar
r pPosted Jul 29, 2013, 3:10 AM
Sanjeeb LenkaPosted Jul 29, 2013, 12:25 AM
ex:
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="Display_xmlfile_gridview_datatable._Default" %>
.CS Code File
using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
namespace Display_xmlfile_gridview_datatable
{
public partial class _Default : System.Web.UI.Page
{
protected void btn_showdata_Click(object sender, EventArgs e)
{
string Path = Server.MapPath("Data.xml");
DataTable dt = new DataTable("student");
dt.Columns.Add("sid", typeof(System.String));
dt.Columns.Add("sname", typeof(System.String));
dt.Columns.Add("saddress", typeof(System.String));
dt.Columns.Add("smarks", typeof(System.String));
dt.ReadXml(Path);
GridView1.DataSource = dt;
GridView1.DataBind();
}
}
}
Data.xml file
Iftikar HussainPosted Jul 28, 2013, 11:53 PM
In your aspx
in you code
Regards,
Iftikar