Linq to XML & ASP.Net - part 8

This is the eighth 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 . You can find the fifth post here . You can find the sixth post here . You can find the seventh post here.

In this post I would like to show on how to use conditions to find a specific element using Linq to XML.

I will use Visual Studio 2010 Ultimate edition and C# as the development language. Visual Studio 2010/2008 express editions will suffice.  


1) Fire VS and create a web site. Choose an appropriate name for your site.

2) In the code behind file Default.aspx.cs, add the namespace

using System.Xml.Linq;

All the classes we need to manipulate XML documents are inside this namespace.

Add the existing students.xml file in your website. You can find this file in the first post. 

We try to find the number of female students.

3) In the Page_Load  event handling routine of the default.aspx.cs file, type the following

 

 XElement xelement = XElement.Load(@"C:\Users\fofo\Documents\
Visual Studio 2010\WebSites\forblog\xml\students.xml");

        var femaleCnt = from sex in xelement.Elements("Student")
                    where (string)sex.Element("Sex") == "Female"
                    select sex;
        Response.Write(femaleCnt.Count());

 

4) Run your application and see in the browser the number of female students.

Email me if you need the source code.

Hope it helps!!!

4 Comments

Comments have been disabled for this content.