Linq to XML & ASP.Net - part 3

This is the third 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 article here .

The xml file we are going to use in all these posts is the students.xml file. You can find the contents of this xml file in the first post.

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

In this third post I will look at how to "Read an element with a specific attribute in an XML document using LINQ to XML".

In this post we want to find the name of the seminars from the students.xml document that have tha attribute "E-Learning"

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

using System.Xml.Linq;

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

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 seminars = from seminar in xelement.Elements("Student")
  where (string)seminar.Element("Seminar").Attribute("Type") == "E-Learning" 
  select seminar;

            Response.Write("Students with seminars of type E-Learning: ");
            Response.Write("<br/>");
            foreach (XElement xEle in seminars)
            {   
                Response.Write(xEle.Element("Seminar").Value);
                Response.Write("<br/>");
 
4) In our LINQ to XML query we see that we access a specific attribute with this line of code. It is pretty straight-forward.
 where (string)seminar.Element("Seminar").Attribute("Type") == "E-Learning" 
5) Run your application and see in the browser the following results. 
Students with seminars of type E-Learning:  
Office 2010
ASP.Net
Silverlight
English


Email me if you need the source code. Hope its helps !!!!

No Comments