Lesson9 Linq 2019
Lesson9 Linq 2019
Lesson9 Linq 2019
The acronym LINQ stands for Language Integrated Query. Microsoft’s query
language is fully integrated and offers easy data access from in-memory objects
//Query syntax:
IEnumerable<int> numQuery1 =
from num in numbers
where num % 2 == 0
orderby num
select num;
//Method syntax:
IEnumerable<int> numQuery2 = numbers.Where(num =>
num % 2 == 0).OrderBy(n => n);
Example 1
var colours = new string[] { "Red", "Orange", "Yellow", "Green", "Blue", "Indigo",
"Violet" };
var longNames = colours.Where(c => c.Length >= 5);
foreach(string s in longNames)
{
Response.WriteLe(s);
}
/* OUTPUT in browser
Orange
Yellow
Green
Indigo
Violet
*/
Another example
Red
IEnumerable<int> topThreeGrades =
grades.OrderByDescending(grade => grade).Take(3);
result: /*
TakeWhile operator
string[] fruits = { "apple", "banana", "mango", "orange",
"passionfruit", "grape" };
IEnumerable<string> query =
fruits.TakeWhile(fruit => String.Compare("orange", fruit, true) != 0);
/*
ا معناها اطبع الفواكه الى ان تصل كلمه
orange
This code produces the following output:
apple
banana
mango
*/
Example 2
The following example creates a sequence with large number of int values:
output
ListBox1.DataSource = departmentList; /
Page.DataBind();
}
Output is:
Example 4
The following code example demonstrates how the standard query operators
can be used to obtain information about a sequence.:
string sentence = "the quick brown fox jumps over the lazy dog";
// Split the string into individual words to create a collection.
string[] words = sentence.Split(' ');
Drag and drop a DataList control into our ASPX page from the data
tab of Visual studio toolbar. In order to display data with DataList
control, we need to first provide an ItemTemplate and
HeaderTemplate with the structure of the data display. I have used
tabular view in this article. Refer the below code.
Next, we can query the database using LINQ query and bind the
DataList control.
Refer the code below,
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
BindEmp();
}
public void BindEmp()
{
EmployeesDataClassesDataContext dbproducts = new
productsDataClassesDataContext();
var LINQQuery = from product in dbproducts.productlists
select product;
DataList1.DataSource = LINQQuery;
DataList1.DataBind();
}
Execute the application. You can see the products data populated in the DataList
control. Refer the below figure.
I have specified the Header style and Alternate row style to apply the style and hence
you can the see the colors.
1. <html>
2. <head runat="server">
3. <title>DataList</title>
4. <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.1
.0/css/bootstrap.min.css">
5. <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js
"></script>
6. <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.0/js/bootstrap.
min.js"></script>
7. <style>
8. .productList {
9. border: 1px solid #6c757d;
10. margin-bottom: 10px;
11. padding: 15px;
12. border-radius: 3px;
13. }
14. </style>
15. </head>
16. <body>
17. <form id="form1" runat="server">
18. <div class="container py-4">
19. <h5 class="text-center text-uppercase">DataList control in asp.net</h5
>
20. <asp:DataList ID="DataList1" runat="server" CssClass="row">
21. <ItemTemplate>
22. <div class="row productList">
23. <div class="col-4">
24. <img alt="" width="250" src='<%#Eval("ProductImage")
%>' />
25. </div>
26. <div class="col-8">
27. <h4><%#Eval("ProductName")%></h4>
28. <h6><%#Eval("ProductPrice")%></h6>
29. <div>
30. <%#Eval("ProductDescription")%>
31. </div>
32. </div>
33. </div>
34. </ItemTemplate>
35. </asp:DataList>
36. </div>
37. </form>
38. </body>
39. </html>
Type filtering
Insert, Update, Delete and Search by Linq with User Store Procedure
Insert, Update, Delete and Search by Linq
There are some steps and code for insert, update, delete and search
by LINQ in SQL SERVER database in ASP.NET:-
Step 1:- We are using SQL SERVER database. So, we need to create
database and table in SQL SERVER as following code:-
USE dbSantoshTest
Step 2:-
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<style type="text/css">
.auto-style1 {
width: 128px;
}
#div {
background-color:#0094ff;
color:white;
font-family:Verdana;
font-size:15px;
}
</style>
</head>
<body>
<form id="form1" runat="server">
<div id="div">
<center>
<h3>Insert, Update, Delete and Search Operation in SQL Server
By LINQ:-</h3>
<table style="height: 246px">
<tr> <td colspan="2"> <asp:Label ID="lblMessage"
runat="server" Font-Bold="true"></asp:Label> </td></tr>
<tr> <td>Name </td> <td class="auto-style1"><asp:TextBox
ID="txtName" runat="server"></asp:TextBox> </td></tr>
<tr> <td>Roll Number </td> <td class="auto-
style1"><asp:TextBox ID="txtRollno" runat="server"
MaxLength="10"></asp:TextBox> </td></tr>
<tr> <td>Contact Number </td> <td class="auto-
style1"><asp:TextBox ID="txtContactNo" runat="server"
MaxLength="10"></asp:TextBox> </td></tr>
<tr> <td>Address </td> <td class="auto-style1"> <asp:TextBox
ID="txtAddress" runat="server"
TextMode="MultiLine"></asp:TextBox></td></tr>
<tr> <td><asp:Button ID="btnInsert" runat="server"
Text="Insert" Width="150px" Font-Bold="true" Height="30px"
OnClick="btnInsert_Click" /> </td> <td class="auto-
style1"><asp:Button ID="btnUpdate" runat="server" Text="Update"
Width="150px" Font-Bold="true" Height="30px"
OnClick="btnUpdate_Click"/> </td></tr>
<tr> <td><asp:Button ID="btnDelete" runat="server"
Text="Delete" Width="150px" Font-Bold="true" Height="30px"
OnClick="btnDelete_Click" /> </td> <td class="auto-
style1"><asp:Button ID="btnSearch" runat="server" Text="Search"
Width="150px" Font-Bold="true" Height="30px"
OnClick="btnSearch_Click"/> </td></tr>
<tr> <td colspan="2"><asp:Button ID="btnClear" runat="server"
Text="Clear" Width="300px" Height="30px" Font-Bold="true" />
</td></tr>
</table>
<br /> <br />
<asp:GridView ID="gvDetail" runat="server"
BackColor="#DEBA84" BorderColor="#DEBA84" BorderStyle="None"
BorderWidth="1px" CellPadding="3" CellSpacing="2">
<FooterStyle BackColor="#F7DFB5"
ForeColor="#8C4510" />
<HeaderStyle BackColor="#A55129" Font-Bold="True"
ForeColor="White" />
<PagerStyle ForeColor="#8C4510"
HorizontalAlign="Center" />
<RowStyle BackColor="#FFF7E7" ForeColor="#8C4510" />
<SelectedRowStyle BackColor="#738A9C" Font-
Bold="True" ForeColor="White" />
<SortedAscendingCellStyle BackColor="#FFF1D4" />
<SortedAscendingHeaderStyle BackColor="#B95C30" />
<SortedDescendingCellStyle BackColor="#F1E5CE" />
<SortedDescendingHeaderStyle BackColor="#93451F" />
</asp:GridView>
</center>
</div>
</form>
</body>
</html>
Step 5:-
Step 6:-
Now, Go to Server Explorer and drag and drop tblLinqTest table on
LinqTestDataClasses.dbml as shown in below image.
<?xml version="1.0"?>
<!--
For more information on how to configure your ASP.NET application,
please visit
http://go.microsoft.com/fwlink/?LinkId=169433
-->
<configuration>
<connectionStrings>
<add name="dbSantoshTestConnectionString" connectionString="Data
Source=PS-PC\SANTOSH;Initial Catalog=dbSantoshTest;Integrated
Security=True"
providerName="System.Data.SqlClient" />
</connectionStrings>
<system.web>
<compilation debug="true" targetFramework="4.0">
<assemblies>
<add assembly="System.Data.Linq, Version=4.0.0.0,
Culture=neutral, PublicKeyToken=B77A5C561934E089"/>
</assemblies>
</compilation>
</system.web>
</configuration>
Step 7:-
}
catch (Exception ex)
{
lblMessage.Text = ex.Message;
LoadRecord();
Clear();
}
}
LoadRecord();
}
catch (Exception ex)
{
lblMessage.Text = ex.Message;
}
}
You can , run the application to perform and Insert, Update, Delete
and Search operation
Using LINQ to XML
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
</div>
<asp:Repeater ID="rssRepeater" runat="server">
<ItemTemplate>
<tr>
NavigateUrl = '<%#Eval("link")%>'
Text = '<%#Eval("title")%>'></asp:HyperLink>
</td>
</tr>
<tr>
<td><hr /></td>
</tr>
<tr>
<td style="background-color:#C2D69B">
Text='<%#Eval("description")%>'></asp:Label>
</td>
</tr>
<tr>
</tr>
</table>
<br />
</ItemTemplate>
</asp:Repeater>
</form>
</body>
</html>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
ds.ReadXml(Server.MapPath("news.xml"));
rssRepeater.DataSource = ds.Tables[0];
rssRepeater.DataBind();
}
WHERE XMLFILE IS LIKE THIS :
</news>
Lets take an example XML file which conatins country and city list.
Take two dropdown lists, the first one has to be filled with counties list by
reading xml. And when user select country from the dropdown, get the cities
list in that country from the xml and bind it to second dropdown.
USA
Input XML :
<?xml version="1.0" encoding="utf-8" ?>
<countries>
<country name='India'>
<city>Delhi</city>
<city>Mumbai</city>
<city>Hyderabad</city>
</country>
<country name='Australia'>
<city>Sydney</city>
<city>Hobart</city>
<city>Canberra</city>
</country>
<country name='Canada'>
<city>Toronto</city>
<city>Niagara</city>
<city>Victoria</city>
</country>
<country name='USA'>
<city>Dallas</city>
<city>Washington</city>
<city>Chicago</city>
</country>
</countries>
LINQ Code :
In PageLoad :
XDocument xdoc = XDocument.Load("D:\\countries.xml");
var countires
= from country in xdoc.Descendants("countries").Elements("coun
try").Attributes("name")
select country.Value;
ddlCountry.DataSource = countires;
ddlCountry.DataBind();
var cities
= from country in xdoc.Descendants("countries").Elements("coun
try")
where country.Attribute("name").Value ==
ddlCountry.SelectedValue
from city in country.Elements("city")
orderby city.Value
select city.Value;
ddlCity.DataSource = cities;
ddlCity.DataBind();
In ddlCountry SelectedIndexChanged :
protected void ddlCountry_SelectedIndexChanged(object sender,
EventArgs e)
{
try
{
XDocument xdoc = XDocument.Load("D:\\countries.xml");
var cities
= from country in xdoc.Descendants("countries").Elements("coun
try")
where country.Attribute("name").Value
== ddlCountry.SelectedValue
from city in country.Elements("city")
orderby city.Value
select city.Value;
ListBox1.DataSource = cities;
ListBox1.DataBind();
}
catch
{
}
}
Example :
Design :
<div>
<asp:GridView ID="gvXML" runat="server" GridLines="Both" CellPadding="5">
</asp:GridView>
</div>
Output :
EmployeeNam
Department Salary
e
Thomas Accounts 5000
Wills Accounts 24000
Brod Finance 28000
Smith Finance 21000
In this example we will check how to apply where condition to filter records in XML by using LINQ.
Example :
Design :
<div>
<asp:GridView ID="gvXML" runat="server" GridLines="Both" CellPadding="5">
</asp:GridView>
</div>
LINQ to XML where condition between to filter records with order by specific column
In this example we will apply where condition to Salary column and get the employee details who are ha
20,000 and 50,000 and order by Salary ascending.
Example :
Design :
<div>
<asp:GridView ID="gvXML" runat="server" GridLines="Both" CellPadding="5">
</asp:GridView>
</div>
Output :
EmployeeNam Designatio
Department Salary
e n
Smith Analyst Finance 21000
Wills Manager Accounts 24000
Previous
I use the Linq technology to read an XML file, but I have a problem when
I try to search something in it.
I would like to know how can I use something such as the "like operator".
var parameters = from param in xferDoc.Descendants("parameter")
where param.Attributes("code").Contains(searchString)
orderby (string)param.Element("description")
select new {
code = param.Attribute("code").Value,
description = param.Element("description").Value,
unit = param.Element("unit").Value
};
Code Snippet
string exampleCode = "BC";
string exampleDescription = "ring";
XElement test = XElement.Load(@"..\..\XMLFile1.xml");
var query = from param in test.Descendants("parameter")
where
((string)param.Attribute("code")).Contains(exampleCode)
||
((string)param.Element("description")).Contains(exampleDescription
)
select new
{
code = (string)param.Attribute("code"),
desc = (string)param.Element("description"),
unit = (string)param.Element("unit")
};
foreach (var item in query)
{
Response.WriteLine("code: {0}; description: {1}; unit:
{2}", item.code, item.desc, item.unit);
}
Code Snippet
XElement root = XElement.Parse(@"<root>
<foo val=""foobar"">1</foo>
<foo val=""baz"">2</foo>
<foo val=""bar"">3</foo>
</root>");
var query = from foo in root.Elements("foo")
where foo.Attribute("val").Value.Contains("bar")
select (int)foo;
foreach (var i in query)
{
response.WriteLe(i);
}
1
3
Code Snippet
<?xml version="1.0" encoding="ISO-8859-1" ?>
- <test>
- <parameters>
- <parameter code="ABC">
<description>Automation</description>
<unit>s</unit>
</parameter>
- <parameter code="EFG">
<description>Engineering</description>
<unit>eng</unit>
</parameter>
- <parameter code="MNO">
<description>Machine</description>
<unit>mac</unit> </parameter>
...
Your first post seemed to search based on the code attribute, now you
say "also try to search something in the description field", so it is not
clear what you want to achieve.
Your XML sample gives us an idea of the XML you want to search,
can you also tell us which value you want to look for? For instance
you have description values like "Automation" or "Engineering", do
you get one of those and want to find the parameter elements
containing such a description? Or do you get only fragments like e.g.
"Auto" and want to find the parameter elements having a description
like "Automation"?
Code Snippet
<?xml version="1.0" encoding="utf-8" ?>
<test>
<parameters>
<parameter code="ABC">
<description>Automation</description>
<unit>s</unit>
</parameter>
<parameter code="EFG">
<description>Engineering</description>
<unit>eng</unit>
</parameter>
<parameter code="MNO">
<description>Machine</description>
<unit>mac</unit>
</parameter>
</parameters>
</test>
Code Snippet
string exampleCode = "BC";
string exampleDescription = "ring";
XElement test = XElement.Load(@"..\..\XMLFile1.xml");
var query = from param in test.Descendants("parameter")
where
((string)param.Attribute("code")).Contains(exampleCode)
||
((string)param.Element("description")).Contains(exampleDescription
)
select new
{
code = (string)param.Attribute("code"),
desc = (string)param.Element("description"),
unit = (string)param.Element("unit")
};
foreach (var item in query)
{
response.WriteLine("code: {0}; description: {1}; unit:
{2}", item.code, item.desc, item.unit);
}
1. example to Read XML file using LINQ to XML
There are two ways to do so: Using the XElement class or the XDocument class.
Both the classes contain the ‘Load()’ method which accepts a file, a URL or
XMLReader and allows XML to be loaded. The primary difference between both
the classes is that an XDocument can contain XML declaration, XML Document
Type (DTD) and processing instructions. Moreover an XDocument contains one
root XElement.
Using XElement
C#
Output:
Using XDocument
C#
XDocument xdocument = XDocument.Load("..\\..\\Employees.xml");
IEnumerable<XElement> employees = xdocument.Elements();
foreach (var employee in employees)
{
Response.WriteLine(employee);
}
Output:
Note 1: As you can observe, XDocument contains a single root element
(Employees).
Note 2: In order to generate an output similar to the one using XElement, use
“xdocument.Root.Elements()” instead of “xdocument.Elements()”
Note 3: VB.NET users can use a new feature called XML Literal.
Let us see how to access the name of all the Employees and list them over here
C#
XElement xelement = XElement.Load("..\\..\\Employees.xml");
IEnumerable<XElement> employees = xelement.Elements();
Response.WriteLine("List of all Employee Names :");
foreach (var employee in employees)
{
Response.WriteLine(employee.Element("Name").Value);
}
Output:
Let us see how to access the name of all Employees and also list the ID along
with it
C#
XElement xelement = XElement.Load("..\\..\\Employees.xml");
IEnumerable<XElement> employees = xelement.Elements();
Response.WriteLine("List of all Employee Names along with their
ID:");
foreach (var employee in employees)
{
Response.WriteLine("{0} has Employee ID {1}",
employee.Element("Name").Value,
employee.Element("EmpId").Value);
}
Output:
C#
XElement xelement = XElement.Load("..\\..\\Employees.xml");
var name = from nm in xelement.Elements("Employee")
where (string)nm.Element("Sex") == "Female"
select nm;
Response.WriteLine("Details of Female Employees:");
foreach (XElement xEle in name)
Response.WriteLine(xEle);
Output:
C#
XElement xelement = XElement.Load("..\\..\\Employees.xml");
var homePhone = from phoneno in xelement.Elements("Employee")
where (string)phoneno.Element("Phone").Attribute("Typ
e") == "Home"
select phoneno;
Response.WriteLine("List HomePhone Nos.");
foreach (XElement xEle in homePhone)
{
Response.WriteLine(xEle.Element("Phone").Value);
}
Output:
Let us see how to find the details of Employees living in 'Alta' City
C#
XElement xelement = XElement.Load("..\\..\\Employees.xml");
var addresses = from address in xelement.Elements("Employee")
where (string)address.Element("Address").Element("Cit
y") == "Alta"
select address;
Response.WriteLine("Details of Employees living in Alta City");
foreach (XElement xEle in addresses)
Response.WriteLine(xEle);
Output:
Let us see how to list all the zip codes in the XML file
C#
XElement xelement = XElement.Load("..\\..\\Employees.xml");
Response.WriteLine("List of all Zip Codes");
foreach (XElement xEle in xelement.Descendants("Zip"))
{
Response.WriteLine((string)xEle);
}
Output:
8. How do I apply Sorting on Elements using LINQ to XML
Let us see how to List and Sort all Zip Codes in ascending order
C#
XElement xelement = XElement.Load("..\\..\\Employees.xml");
IEnumerable<string> codes
= from code in xelement.Elements("Employee")
let zip =
(string)code.Element("Address").Element("Zip")
orderby zip
select zip;
Response.WriteLine("List and Sort all Zip Codes");
foreach (string zp in codes)
Response.WriteLine(zp);
Output:
When you need to create an XML document containing XML declaration, XML
Document Type (DTD) and processing instructions, Comments, Namespaces, you
should go in for the XDocument class.
C#
XNamespace empNM = "urn:lst-emp:emp";
XDocument xDoc = new XDocument(
new XDeclaration("1.0", "UTF-16", null),
new XElement(empNM + "Employees",
new XElement("Employee",
new XComment("Only 3 elements for demo
purposes"),
new XElement("EmpId", "5"),
new XElement("Name", "Kimmy"),
new XElement("Sex", "Female")
)));
StringWriter sw = new StringWriter();
xDoc.Save(sw);
Use the following code to save the XML to a XMLWriter or to your physical disk
C#
XNamespace empNM = "urn:lst-emp:emp";
XDocument xDoc = new XDocument(
new XDeclaration("1.0", "UTF-16", null),
new XElement(empNM + "Employees",
new XElement("Employee",
new XComment("Only 3 elements for demo
purposes"),
new XElement("EmpId", "5"),
new XElement("Name", "Kimmy"),
new XElement("Sex", "Female")
)));
StringWriter sw = new StringWriter();
XmlWriter xWrite = XmlWriter.Create(sw);
xDoc.Save(xWrite);
xWrite.Close();
// Save to Disk
xDoc.Save("C:\\Something.xml");
Response.WriteLine("Saved");
11. Load an XML Document using XML Reader using LINQ to XML
Use the following code to load the XML Document into an XML Reader
C#
XmlReader xRead = XmlReader.Create(@"..\\..\\Employees.xml");
XElement xEle = XElement.Load(xRead);
Response.WriteLine(xEle);
xRead.Close();
C#
// Using XElement
Response.WriteLine("Using XElement");
XElement xEle = XElement.Load("..\\..\\Employees.xml");
var emp1 = xEle.Descendants("Employee").ElementAt(1);
Response.WriteLine(emp);
Response.WriteLine("------------");
//// Using XDocument
Response.WriteLine("Using XDocument");
XDocument xDoc = XDocument.Load("..\\..\\Employees.xml");
var emp1 = xDoc.Descendants("Employee").ElementAt(1);
Response.WriteLine(emp);
C#
XElement xEle = XElement.Load("..\\..\\Employees.xml");
var emps = xEle.Descendants("Employee").Take(2);
foreach (var emp in emps)
Response.WriteLine(emp);
14. List the 2nd and 3rd Element using LINQ to XML
C#
XElement xEle = XElement.Load("..\\..\\Employees.xml");
var emps = xEle.Descendants("Employee").Skip(1).Take(2);
foreach (var emp in emps)
Response.WriteLine(emp);
C#
XElement xEle = XElement.Load("..\\..\\Employees.xml");
var emps = xEle.Descendants("Employee").Reverse().Take(2);
foreach (var emp in emps)
Response.WriteLine(emp.Element("EmpId") + "" +
emp.Element("Name"));
To display only the values without the XML tags, use the ‘Value’ property
C#
XElement xEle = XElement.Load("..\\..\\Employees.xml");
var emps = xEle.Descendants("Employee").Reverse().Take(2);
foreach (var emp in emps)
Response.WriteLine(emp.Element("EmpId").Value + ". " +
emp.Element("Name").Value);
If you notice, the results are not ordered i.e. the Employee 4 is printed before 3.
To order the results, just add call Reverse() again while filtering as shown below:
C#
XElement xEle = XElement.Load("..\\..\\Employees.xml");
var emps =
xEle.Descendants("Employee").Reverse().Take(2).Reverse();
foreach (var emp in emps)
Response.WriteLine(emp.Element("EmpId").Value + ". " +
emp.Element("Name").Value);
16. Find the Element Count based on a condition using LINQ to XML
C#
XElement xelement = XElement.Load("..\\..\\Employees.xml");
var stCnt = from address in xelement.Elements("Employee")
where (string)address.Element("Address").Element("State")
== "CA"
select address;
Response.WriteLine("No of Employees living in CA State are {0}",
stCnt.Count());
17. Add a new Element at runtime using LINQ to XML
You can add a new Element to an XML document at runtime by using the Add()
method of XElement. The new Element gets added as the last element of the XML
document.
C#
XElement xEle = XElement.Load("..\\..\\Employees.xml");
xEle.Add(new XElement("Employee",
new XElement("EmpId", 5),
new XElement("Name", "George")));
Response.Write(xEle);
18. Add a new Element as the First Child using LINQ to XML
In the previous example, by default the new Element gets added to the end of
the XML document. If you want to add the Element as the First Child, use the
‘AddFirst()’ method
C#
XElement xEle = XElement.Load("..\\..\\Employees.xml");
xEle.AddFirst(new XElement("Employee",
new XElement("EmpId", 5),
new XElement("Name", "George")));
Response.Write(xEle);
C#
XElement xEle = XElement.Load("..\\..\\Employees.xml");
xEle.Add(new XElement("Employee",
new XElement("EmpId", 5),
new XElement("Phone", "423-555-4224", new XAttribute("Type",
"Home"))));
Response.Write(xEle);
Let us say that in the XML file, you want to change the Country from “USA” to
“United States of America” for all the Elements. Here’s how to do so:
C#
XElement xEle = XElement.Load("..\\..\\Employees.xml");
var countries =
xEle.Elements("Employee").Elements("Address").Elements("Country").ToL
ist();
foreach (XElement cEle in countries)
cEle.ReplaceNodes("United States Of America");
Response.Write(xEle);
21. Remove an attribute from all the Elements using LINQ to XML
Let us say if you want to remove the Type attribute ( <Phone Type=”Home”>)
attribute for all the elements, then here’s how to do it.
C#
XElement xEle = XElement.Load("..\\..\\Employees.xml");
var phone = xEle.Elements("Employee").Elements("Phone").ToList();
foreach (XElement pEle in phone)
pEle.RemoveAttributes();
Response.Write(xEle);
If you want to delete an entire element based on a condition, here’s how to do it.
We are deleting the entire Address Element
C#
XElement xEle = XElement.Load("..\\..\\Employees.xml");
var addr = xEle.Elements("Employee").ToList();
foreach (XElement addEle in addr)
addEle.SetElementValue("Address", null);
Response.Write(xEle);
SetElementValue() can also be used to Update the content of an Element.
If you have a requirement where you have to remove ‘n’ number of Elements; For
E.g. To remove the last 2 Elements, then here’s how to do it
C#
XElement xEle = XElement.Load("..\\..\\Employees.xml");
var emps = xEle.Descendants("Employee");
emps.Reverse().Take(2).Remove();
Response.Write(xEle);
All the manipulations we have done so far were in the memory and were not
persisted in the XML file. If you have been wondering how to persist changes to
the XML, once it is modified, then here’s how to do so. It’s quite simple. You just
need to call the Save() method. It’s also worth observing that the structure of the
code shown below is similar to the structure of the end result (XML document).
That’s one of the benefits of LINQ to XML, that it makes life easier for developers
by making it so easy to create and structure XML documents.
C#
XElement xEle = XElement.Load("..\\..\\Employees.xml");
xEle.Add(new XElement("Employee",
new XElement("EmpId", 5),
new XElement("Name", "George"),
new XElement("Sex", "Male"),
new XElement("Phone", "423-555-4224", new XAttribute("Type", "Hom
e")),
new XElement("Phone", "424-555-0545", new XAttribute("Type", "Wor
k")),
new XElement("Address",
new XElement("Street", "Fred Park, East Bay"),
new XElement("City", "Acampo"),
new XElement("State", "CA"),
new XElement("Zip", "95220"),
new XElement("Country", "USA"))));
xEle.Save("..\\..\\Employees.xml");
Response.WriteLe(xEle);