Hi guys, today I will show you one demo on LINQ to XML, this
is very very helpful for the beginners who are trying to learn LINQ. Here I
have prepared one demo like I have a xml file with list of employees, when a
user give the employee ID it should populate the employee Name.
First Create a XML File
<?xml version="1.0" encoding="utf-8" ?>
<Employees>
<Employee>
<ID>001</ID>
<Name>Rohit</Name>
</Employee>
<Employee>
<ID>002</ID>
<Name>Sam</Name>
</Employee>
<Employee>
<ID>003</ID>
<Name>Jonshon</Name>
</Employee>
<Employee>
<ID>004</ID>
<Name>Rocky</Name>
</Employee>
</Employees>
|
Then design the page like this
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0
Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
Enter
ID :
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="Submit" />
<br />
<br />
<asp:Label ID="Label1" runat="server"></asp:Label>
</div>
</form>
</body>
</html>
|
Now write the following code in the aspx.cs file
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Xml;
using System.Xml.Linq;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
XElement obj = XElement.Load(Server.MapPath("~/XMLFile.xml"));
string employeeName= obj.Descendants("Employee")
.Where(x => (string)x.Element("ID") == TextBox1.Text)
.Select(x=>(string)x.Element("Name")).SingleOrDefault();
if (!string.IsNullOrEmpty(employeeName))
{
Label1.Text = employeeName;
}
else
{
Label1.Text = "No Employee";
}
}
}
|
Demo