Support us .Net Basics C# SQL ASP.NET ADO.NET MVC Slides C# Programs Subscribe Buy DVD

Part 3 - Querying xml document using linq to xml

Suggested Videos
Part 1 - LINQ to XML
Part 2 - Creating an XML document using in-memory collection of objects



In Parts 1 and 2 of LINQ to XML tutorial, we discussed creating XML documents using LINQ to XML. 



The following is the XML document that we created in Part 1
<?xml version="1.0" encoding="utf-8" standalone="yes"?>
<!--Creating an XML Tree using LINQ to XML-->
<Students>
  <Student Id="101">
    <Name>Mark</Name>
    <Gender>Male</Gender>
    <TotalMarks>800</TotalMarks>
  </Student>
  <Student Id="102">
    <Name>Rosy</Name>
    <Gender>Female</Gender>
    <TotalMarks>900</TotalMarks>
  </Student>
  <Student Id="103">
    <Name>Pam</Name>
    <Gender>Female</Gender>
    <TotalMarks>850</TotalMarks>
  </Student>
  <Student Id="104">
    <Name>John</Name>
    <Gender>Male</Gender>
    <TotalMarks>950</TotalMarks>
  </Student>
</Students>

In this video, we will discuss how to query xml document using linq to xml. We want to retrieve all the student names who has TotalMarks greater than 800. Students names should be sorted by TotalMarks in descending order.


IEnumerable<string> names = from student in XDocument
                                                                                     .Load(@"C:\Demo\Demo\Data.xml")
                                                                                     .Descendants("Student")
                                                     where (int)student.Element("TotalMarks") > 800
                                                     orderby (int)student.Element("TotalMarks") descending
                                                     select student.Element("Name").Value;

foreach (string name in names)
{
    Console.WriteLine(name);
}

Output : 
linq to xml query example

Alternate way of writing the above query. Change is highlighted in yellow color.
IEnumerable<string> names = from student in XDocument
                                                                                      .Load(@"C:\Demo\Demo\Data.xml")
                                                                                      .Element("Students")
                                                                                      .Elements("Student")
                                                     where (int)student.Element("TotalMarks") > 800
                                                     orderby (int)student.Element("TotalMarks") descending
                                                     select student.Element("Name").Value;

LINQ to XML tutorial

No comments:

Post a Comment

If you like this website, please share with your friends on facebook and Google+ and recommend us on google using the g+1 button on the top right hand corner.