9866550012
CSHARP LINQ OPERATIONS
Employees.xml is as follows:
<?xml version="1.0" encoding="utf-8" ?>
<Employees>
<Employee>
<EmpId>1</EmpId>
<Name>Sam</Name>
<Sex>Male</Sex>
<Phone Type="Home">423-555-0124</Phone>
<Phone Type="Work">424-555-0545</Phone>
<Address>
<Street>7A Cox Street</Street>
<City>Acampo</City>
<State>CA</State>
<Zip>95220</Zip>
<Country>USA</Country>
</Address>
</Employee>
<Employee>
<EmpId>2</EmpId>
<Name>Lucy</Name>
<Sex>Female</Sex>
<Phone Type="Home">143-555-0763</Phone>
<Phone Type="Work">434-555-0567</Phone>
<Address>
<Street>Jess Bay</Street>
<City>Alta</City>
<State>CA</State>
<Zip>95701</Zip>
<Country>USA</Country>
</Address>
</Employee>
<Employee>
<EmpId>3</EmpId>
<Name>Kate</Name>
<Sex>Female</Sex>
<Phone Type="Home">166-555-0231</Phone>
<Phone Type="Work">233-555-0442</Phone>
<Address>
<Street>23 Boxen Street</Street>
<City>Milford</City>
<State>CA</State>
<Zip>96121</Zip>
<Country>USA</Country>
</Address>
</Employee>
<Employee>
<EmpId>4</EmpId>
<Name>Chris</Name>
<Sex>Male</Sex>
<Phone Type="Home">564-555-0122</Phone>
<Phone Type="Work">442-555-0154</Phone>
<Address>
<Street>124 Kutbay</Street>
<City>Montara</City>
<State>CA</State>
<Zip>94037</Zip>
<Country>USA</Country>
</Address>
</Employee>
</Employees>
Read XML and Traverse the XML Document using LINQ To XML
1. How Do I Read XML 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#
XElement xelement = XElement.Load("..\\..\\Employees.xml");
IEnumerable<XElement> employees = xelement.Elements();
// Read the entire XML
foreach (var employee in employees)
{
Console.WriteLine(employee);
}
Output:
Using XDocument
C#
XDocument xdocument = XDocument.Load("..\\..\\Employees.xml");
IEnumerable<XElement> employees = xdocument.Elements();
foreach (var employee in employees)
{
Console.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()”
2. How Do I Access a Single Element using LINQ to XML
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();
Console.WriteLine("List of all Employee Names :");
foreach (var employee in employees)
{
Console.WriteLine(employee.Element("Name").Value);
}
Output:
3. How Do I Access Multiple Elements using LINQ to XML
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();
Console.WriteLine("List of all Employee Names along with their ID:");
foreach (var employee in employees)
{
Console.WriteLine("{0} has Employee ID {1}",
employee.Element("Name").Value,
employee.Element("EmpId").Value);
}
Output:
4. How Do I Access all Elements having a Specific Attribute using LINQ to XML
Let us see how to access details of all Female Employees
C#
XElement xelement = XElement.Load("..\\..\\Employees.xml");
var name = from nm in xelement.Elements("Employee")
where (string)nm.Element("Sex") == "Female"
select nm;
Console.WriteLine("Details of Female Employees:");
foreach (XElement xEle in name)
Console.WriteLine(xEle);
Output:
5. How Do I access Specific Element having a Specific Attribute using LINQ to XML
Let us see how to list all the Home Phone Nos.
C#
XElement xelement = XElement.Load("..\\..\\Employees.xml");
var homePhone = from phoneno in xelement.Elements("Employee")
where (string)phoneno.Element("Phone").Attribute("Type") == "Home"
select phoneno;
Console.WriteLine("List HomePhone Nos.");
foreach (XElement xEle in homePhone)
{
Console.WriteLine(xEle.Element("Phone").Value);
}
Output:
6. How Do I Find an Element within another Element using LINQ to XML
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("City") == "Alta"
select address;
Console.WriteLine("Details of Employees living in Alta City");
foreach (XElement xEle in addresses)
Console.WriteLine(xEle);
Output:
7. How Do I Find Nested Elements (using Descendants Axis) using LINQ to XML
Let us see how to list all the zip codes in the XML file
C#
XElement xelement = XElement.Load("..\\..\\Employees.xml");
Console.WriteLine("List of all Zip Codes");
foreach (XElement xEle in xelement.Descendants("Zip"))
{
Console.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;
Console.WriteLine("List and Sort all Zip Codes");
foreach (string zp in codes)
Console.WriteLine(zp);
Output:
Section 2: Manipulate XML content and Persist the changes using LINQ To XML
9. Create an XML Document with Xml Declaration/Namespace/Comments using LINQ to XML
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);
Console.WriteLine(sw);
10. Save the XML Document to a XMLWriter or to the disk using LINQ to XML
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");
Console.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);
Console.WriteLine(xEle);
xRead.Close();
12. Find Element at a Specific Position using LINQ to XML
Find the 2nd Employee Element
C#
// Using XElement
Console.WriteLine("Using XElement");
XElement xEle = XElement.Load("..\\..\\Employees.xml");
var emp1 = xEle.Descendants("Employee").ElementAt(1);
Console.WriteLine(emp);
Console.WriteLine("------------");
//// Using XDocument
Console.WriteLine("Using XDocument");
XDocument xDoc = XDocument.Load("..\\..\\Employees.xml");
var emp1 = xDoc.Descendants("Employee").ElementAt(1);
Console.WriteLine(emp);
13. List the First 2 Elements using LINQ to XML
List the details of the first 2 Employees
C#
XElement xEle = XElement.Load("..\\..\\Employees.xml");
var emps = xEle.Descendants("Employee").Take(2);
foreach (var emp in emps)
Console.WriteLine(emp);
14. List the 2nd and 3rd Element using LINQ to XML
List the 2nd and 3rd Employees
C#
XElement xEle = XElement.Load("..\\..\\Employees.xml");
var emps = xEle.Descendants("Employee").Skip(1).Take(2);
foreach (var emp in emps)
Console.WriteLine(emp);
15. List the Last 2 Elements using LINQ To XML
We have been posting the entire elements as output in our previous examples. Let us say that you want to display only the Employee Name, use this query:
C#
XElement xEle = XElement.Load("..\\..\\Employees.xml");
var emps = xEle.Descendants("Employee").Reverse().Take(2);
foreach (var emp in emps)
Console.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)
Console.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)
Console.WriteLine(emp.Element("EmpId").Value + ". " + emp.Element("Name").Value);
16. Find the Element Count based on a condition using LINQ to XML
Count the number of Employees living in the state CA
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;
Console.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")));
Console.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")));
Console.Write(xEle);
19. Add an attribute to an Element using LINQ to XML
To add an attribute to an Element, use the following code:
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"))));
Console.Write(xEle);
20. Replace Contents of an Element/Elements using LINQ to XML
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").ToList();
foreach (XElement cEle in countries)
cEle.ReplaceNodes("United States Of America");
Console.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();
Console.Write(xEle);
To remove attribute of one Element based on a condition, traverse to that Element and SetAttributeValue("Type", null); You can also use SetAttributeValue(XName,object) to update an attribute value.
22. Delete an Element based on a condition using LINQ to XML
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);
Console.Write(xEle);
SetElementValue() can also be used to Update the content of an Element.
23. Remove ‘n’ number of Elements using LINQ to XML
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();
Console.Write(xEle);
24. Save/Persists Changes to the XML using LINQ to XML
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", "Home")),
new XElement("Phone", "424-555-0545", new XAttribute("Type", "Work")),
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");
Console.WriteLine(xEle);
Console.ReadLine();
2.
Data.Xml <?xml version="1.0" encoding="utf-8" ?>
<catalog>
<books>
<book id="bk101">
<author id="1">Gambardella, Matthew</author>
<title>XML Developer's Guide</title>
<genre>Computer</genre>
<price>44.95</price>
<publish_date>2000-10-01</publish_date>
<description> An in-depth look at creating applications with XML.</description>
</book>
<book id="bk102">
<author id="2">Ralls, Kim</author>
<title>Midnight Rain</title>
<genre>Fantasy</genre>
<price>5.95</price>
<publish_date>2000-12-16</publish_date>
<description> A former architect battles corporate zombies,an evil sorceress, and her own childhood to become
queen of the world.</description>
</book>
<book id="bk103">
<author id="3">Corets, Eva</author>
<title>Maeve Ascendant</title>
<genre>Fantasy</genre>
<price>5.95</price>
<publish_date>2000-11-17</publish_date>
<description>After the collapse of a nanotechnology society in England, the young survivors lay the foundation for
a new society. </description>
</book>
<book id="bk104">
<author id="4">Corets, Eva</author>
<title>Oberon's Legacy</title>
<genre>Fantasy</genre>
<price>5.95</price>
<publish_date>2001-03-10</publish_date>
<description>In post-apocalypse England, the mysterious agent known only as Oberon helps to create a new life for
the inhabitants of London. Sequel to Maeve Ascendant.</description>
</book>
<book id="bk105">
<author id="5">Corets, Eva</author>
<title>The Sundered Grail</title>
<genre>Fantasy</genre>
<price>5.95</price>
<publish_date>2001-09-10</publish_date>
<description>The two daughters of Maeve, half-sisters, battle one another for control of England. Sequel to
Oberon's Legacy.</description>
</book>
</books>
</catalog>
Fetching all the Books
To fetch all the books, we just need to parse the XML file. Find the descendants book and fetch it into an anonymous class.

Fetching a Particular Book
If you want to fetch a particular book, we need to apply a where condition while parsing the XML file.

Fetching the Attribute Value of a particular Book
Imagine you need to fetch the author Id of the book with Id bk102. To do that you need to select as below:

Fetching all the Authors Name only
To fetch the entire author name, we need to execute the following query.

For your reference thefull source code is as below:
Program.cs using System;
using System.Linq;
using System.Xml.Linq;
namespace ConsoleApplication23
{
class Program
{
static void Main(string[] args)
{
XDocument document = XDocument.Load("D:\\Data.xml");
#region Fetch All the Books
var books = from r in document.Descendants("book")
select new
{
Author = r.Element("author").Value,
Title = r.Element("title").Value,
Genere = r.Element("genre").Value,
Price = r.Element("price").Value,
PublishDate = r.Element("publish_date").Value,
Description = r.Element("description").Value,
};
foreach (var r in books)
{
Console.WriteLine(r.PublishDate + r.Title + r.Author);
}
Console.ReadKey(true);
#endregion
#region Fetching a particular Book
var selectedBook = from r in document.Descendants("book").Where
(r=>(string)r.Attribute("id")=="bk102")
select new
{
Author = r.Element("author").Value,
Title = r.Element("title").Value,
Genere = r.Element("genre").Value,
Price = r.Element("price").Value,
PublishDate = r.Element("publish_date").Value,
Description = r.Element("description").Value,
};
foreach (var r in selectedBook)
{
Console.WriteLine(r.PublishDate + r.Title + r.Author);
}
Console.ReadKey(true);
#endregion
#region Fetching a particular Book
var selectedBookAttribute = (from r in document.Descendants("book").Where
(r => (string)r.Attribute("id") == "bk102")
select r.Element("author").Attribute("id").Value).FirstOrDefault();
Console.WriteLine(selectedBookAttribute);
Console.ReadKey(true);
#endregion
#region Fetching all Authors
var allauthors = from r in document.Descendants("book")
select r.Element("author").Value;
foreach(var r in allauthors)
{
Console.WriteLine(r.ToString());
}
Console.ReadKey(true);
#endregion
}
}
}
Output

<catalog>
<books>
<book id="bk101">
<author id="1">Gambardella, Matthew</author>
<title>XML Developer's Guide</title>
<genre>Computer</genre>
<price>44.95</price>
<publish_date>2000-10-01</publish_date>
<description> An in-depth look at creating applications with XML.</description>
</book>
<book id="bk102">
<author id="2">Ralls, Kim</author>
<title>Midnight Rain</title>
<genre>Fantasy</genre>
<price>5.95</price>
<publish_date>2000-12-16</publish_date>
<description> A former architect battles corporate zombies,an evil sorceress, and her own childhood to become
queen of the world.</description>
</book>
<book id="bk103">
<author id="3">Corets, Eva</author>
<title>Maeve Ascendant</title>
<genre>Fantasy</genre>
<price>5.95</price>
<publish_date>2000-11-17</publish_date>
<description>After the collapse of a nanotechnology society in England, the young survivors lay the foundation for
a new society. </description>
</book>
<book id="bk104">
<author id="4">Corets, Eva</author>
<title>Oberon's Legacy</title>
<genre>Fantasy</genre>
<price>5.95</price>
<publish_date>2001-03-10</publish_date>
<description>In post-apocalypse England, the mysterious agent known only as Oberon helps to create a new life for
the inhabitants of London. Sequel to Maeve Ascendant.</description>
</book>
<book id="bk105">
<author id="5">Corets, Eva</author>
<title>The Sundered Grail</title>
<genre>Fantasy</genre>
<price>5.95</price>
<publish_date>2001-09-10</publish_date>
<description>The two daughters of Maeve, half-sisters, battle one another for control of England. Sequel to
Oberon's Legacy.</description>
</book>
</books>
</catalog>
Fetching all the Books
To fetch all the books, we just need to parse the XML file. Find the descendants book and fetch it into an anonymous class.
Fetching a Particular Book
If you want to fetch a particular book, we need to apply a where condition while parsing the XML file.
Fetching the Attribute Value of a particular Book
Imagine you need to fetch the author Id of the book with Id bk102. To do that you need to select as below:
Fetching all the Authors Name only
To fetch the entire author name, we need to execute the following query.
For your reference thefull source code is as below:
Program.cs using System;
using System.Linq;
using System.Xml.Linq;
namespace ConsoleApplication23
{
class Program
{
static void Main(string[] args)
{
XDocument document = XDocument.Load("D:\\Data.xml");
#region Fetch All the Books
var books = from r in document.Descendants("book")
select new
{
Author = r.Element("author").Value,
Title = r.Element("title").Value,
Genere = r.Element("genre").Value,
Price = r.Element("price").Value,
PublishDate = r.Element("publish_date").Value,
Description = r.Element("description").Value,
};
foreach (var r in books)
{
Console.WriteLine(r.PublishDate + r.Title + r.Author);
}
Console.ReadKey(true);
#endregion
#region Fetching a particular Book
var selectedBook = from r in document.Descendants("book").Where
(r=>(string)r.Attribute("id")=="bk102")
select new
{
Author = r.Element("author").Value,
Title = r.Element("title").Value,
Genere = r.Element("genre").Value,
Price = r.Element("price").Value,
PublishDate = r.Element("publish_date").Value,
Description = r.Element("description").Value,
};
foreach (var r in selectedBook)
{
Console.WriteLine(r.PublishDate + r.Title + r.Author);
}
Console.ReadKey(true);
#endregion
#region Fetching a particular Book
var selectedBookAttribute = (from r in document.Descendants("book").Where
(r => (string)r.Attribute("id") == "bk102")
select r.Element("author").Attribute("id").Value).FirstOrDefault();
Console.WriteLine(selectedBookAttribute);
Console.ReadKey(true);
#endregion
#region Fetching all Authors
var allauthors = from r in document.Descendants("book")
select r.Element("author").Value;
foreach(var r in allauthors)
{
Console.WriteLine(r.ToString());
}
Console.ReadKey(true);
#endregion
}
}
}
Output
3.
<?xml version="1.0" encoding="utf-8" standalone="yes"?>
<!--Jason's xml-->
<People>
<Person id="1">
<Name>Joe</Name>
<Age>35</Age>
<Job>Manager</Job>
</Person>
<Person id="2">
<Name>Jason</Name>
<Age>18</Age>
<Job>Software Engineer</Job>
</Person>
<Person id="3">
<Name>Lisa</Name>
<Age>53</Age>
<Job>Bakery Owner</Job>
</Person>
<Person id="4">
<Name>Mary</Name>
<Age>90</Age>
<Job>Nurse</Job>
</Person>
</People>
//create xml document from scratch |
02 |
03 | XDocument document = new XDocument( |
04 |
05 | new XDeclaration("1.0", "utf-8", "yes"), |
06 |
07 | new XComment("Jason's xml"), |
08 |
09 | new XElement("People", |
10 |
11 | new XElement("Person", newXAttribute("id", 1), |
12 | new XElement("Name","Joe"), |
13 | new XElement("Age", 35), |
14 | new XElement("Job","Manager") |
15 | ), |
16 | new XElement("Person", newXAttribute("id", 2), |
17 | new XElement("Name","Jason"), |
18 | new XElement("Age", 18), |
19 | new XElement("Job","Software Engineer") |
20 | ), |
21 | new XElement("Person", newXAttribute("id", 3), |
22 | new XElement("Name","Lisa"), |
23 | new XElement("Age", 53), |
24 | new XElement("Job","Bakery Owner") |
25 | ), |
26 | new XElement("Person", newXAttribute("id", 4), |
27 | new XElement("Name","Mary"), |
28 | new XElement("Age", 90), |
29 | new XElement("Job","Nurse") |
30 | ) |
31 |
32 | ) |
33 | |
34 | ); |
35 |
36 | //save constructed document |
37 | document.Save("People.xml"); |
No comments:
Post a Comment