Nikolaos Kantzelis ASP.Net Blog

This blog will focus on ASP.NET Framework


About Me

Great Blogs

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;


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!!!

Posted: Sep 23 2010, 04:27 PM by nikolaosk | with 4 comment(s) |
Filed under: , ,


Crack said:

Hello amigos, I am Anna and I want to make my little commentary. I am want to place your text at my personal blog, with link to your blog. Is it normal for your? give to me your answer, please.

# September 23, 2010 1:52 PM

John said:

Nice post to start with using LINQ to xml

# September 24, 2010 8:16 AM

nikolaosk said:

Hello Anna,

I am glad to tell you that you can place text from my blog to yours but you must always mention my blog and place a link directly to the original blog post. When you finish with the first post email me.

# September 24, 2010 7:54 PM

gouri said:

nice post for starting with Linq

# April 25, 2013 7:40 AM