Reading Selected Elements from XML
|
We are going to explain about reading the data from xml and filtering particular element and binding into Grid view using ASP.NET ,C#.We can achieve this using Dynamic Data table.We have to create a data table and data row.Lets see how to achieve this in few steps. |
Step 1. Add and Dropdownlist control ,Gridview Control and Button.
Step 2. Here I have Created an XML file named places.xml .
Step 3. It includes the following Elements.
- Id
- Country
- City
|
Step 4. The Dropdown Control contains the Country to filter the city. |
|
| |
|
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
XmlDocument doc = new XmlDocument();
doc.Load(Server.MapPath("place.xml"));
XmlNodeList bookList = doc.GetElementsByTagName("Place");
foreach (XmlNode node in bookList)
{
XmlElement bookElement = (XmlElement)node;
string ctry=bookElement.GetElementsByTagName("Country")
[0].InnerText;
ddl.Items.Add(ctry);
}
}
}
|
|
The above code is used to bind the Country first in the Dropdown list.
|
Step 5. Create and Data table and add the Coulmns (1) Id (2) City and in the Button Click add the following Code. |
|
|
|
|
protected void Button1_Click(object sender, EventArgs e)
{
DataTable dt = new DataTable();
DataColumn dc = new DataColumn("Id");
DataColumn dc1 = new DataColumn("Name");
dt.Columns.Add(dc);
dt.Columns.Add(dc1);
string ct = ddl.SelectedItem.ToString();
string dataPath = Server.MapPath("place.xml");
DataSet dSet = new DataSet();
dSet.ReadXml(dataPath);
DataRow[] rows = dSet.Tables[0].Select(" Name = '" + ct + "'");
foreach (DataRow dr in rows)
{
DataRow myRow = dt.NewRow();
myRow["Id"] = dr["Id"];
myRow["Name"] = dr["Name"];
dt.Rows.Add(myRow);
}
grxml.DataSource = dt;
grxml.DataBind();
}
|
| Step 6. The Xml file as follow as |
|
<?xml version="1.0" encoding="utf-8" ?>
<Places>
<Place>
<Id> 1 </Id>
<City>Chennai</City>
<Country>INDIA </Country>
</Place>
<Place>
<Id> 2 </Id>
<City> Atlanta </City>
<Country>USA </Country>
</Place>
</Places>
|
| Step 7. The Inline code as shows below |
|
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Readxml.aspx.cs"
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>Reading XML</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:DropDownList ID="ddl" runat="server"></asp:DropDownList> <br />
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Button" />
</div>
</asp:GridView>
</form>
</body>
</html>
|