ASP:NET Reading XML Data into a DataSet object To GridView in C#

In ASP.NET you have a number of options by which you can easily read an XML Document and display an XML document in DataGrid, GridView, Repeater Control, DropDown List etc or any other control according to your requirements.
Here i will import an xml document using an inbuilt function of dataset and display the data in a GridView Control.

 

Here is the sample XML file named “country.xml” that i am using

<?xml version=”1.0″ encoding=”ISO-8859-1″?>

<countries>

<country>
<text>Norway</text>
<value>N</value>
</country>

<country>
<text>Sweden</text>
<value>S</value>
</country>

<country>
<text>France</text>
<value>F</value>
</country>

<country>
<text>Italy</text>
<value>I</value>
</country>

</countries>

Here is the code for your Default.aspx.cs page

void Page_Load(Object sender, EventArgs e)
{

DataSet CountryDataSet = new DataSet();
string filePath = Server.MapPath(“country.xml”);

//Read the contents of the XML file into the DataSet

CountryDataSet.ReadXml(filePath);
CountryGrid.DataSource = CountryDataSet.Tables[0].DefaultView;
CountryGrid.DataBind();

}

Here is the code for your Default.aspx page

< html xmlns=”http://www.w3.org/1999/xhtml” >
< head runat=”server” >
< title >ASP:NET Reading XML Data into a DataSet object To GridView< /title >
< /head >

< body >

< form id=”form1″ runat=”server” >
< div >

< asp:GridView id=”CountryGrid”  runat=”server” AutoGenerateColumns=”False” CellPadding=”4″            HeaderStyle-BackColor=”blue”  HeaderStyle-ForeColor=”White”  HeaderStyle-HorizontalAlign=”Center” HeaderStyle-Font-Bold=”True” >
< Columns >

< asp:BoundField HeaderText=”Country” DataField=”text” / >

< asp:BoundField HeaderText=”Value” DataField=”value” ItemStyle-HorizontalAlign=”Right” / >

< /Columns >
< /asp:GridView >

< /div >
< /form >
< /body >
< /html >