Linq to XML & ASP.Net - part 5
This is the fifth post in a new series of posts regarding LINQ to XML and ASP.Net.Please do read the first post here. You can find the second post here . You can find the third post here . You can read the fourth post here . I
will use Visual Studio 2010 Ultimate edition and C# as the development
language. Visual Studio 2010/2008 express editions will suffice. In this fourth post I will look at how to "How to find elements in a specific position within an xml file using LINQ to XML". 1) Fire VS and create a web site. Choose an appropriate name for your site. 2) Add the existing students.xml file in your website. 3) In the code behind file Default.aspx.cs, add the namespace All the classes we need to manipulate XML documents are inside this namespace. In this first example we want to find the the information of the second element In the Page_Load event handling routine of the default.aspx.cs file, type the followingusing System.Xml.Linq;
XElement xelement = XElement.Load(@"C:\Users\fofo\Documents\
Visual Studio 2010\WebSites\forblog\xml\students.xml");
var student = xelement.Descendants("Student").ElementAt(1);
Response.Write(student);
4) We use the ElementAt method to return an element at a specified index at a sequence. The output of this LINQ to XML query will be
2 Mary Female ASP.Net Physics
So we get back all the information for the second student in the xml document.
5) Let's try another example. What if we wanted to list the first 2 elements and all their data?Comment out these lines of code
var student = xelement.Descendants("Student").ElementAt(1);
Response.Write(student);and type
var students = xelement.Descendants("Student").Take(2);
foreach (var student in students)
Response.Write(student);
Take operator gets the first x number of elements in a sequence.Run your application and see in the browser the following results.
1 nikos Male Office 2010 Maths
2 Mary
Female ASP.Net Physics
Email me if you need the source code. Hope its helps !!!!