Linq to XML & ASP.Net - part 1

I am going to write a new series of articles regarding LINQ to XML and how to use it in ASP.Net web sites.

I am not going into details what LINQ is or what LINQ to XML is. LINQ is a technology that is an established 3 years old technology.If you google these terms you will find thousands of references.

So I strongly suggest you to do so before reading any further. I am providing some basic links.

LINQ to XML uses LINQ syntax to generate, read, and sort XML data. LINQ to XML uses its own set of objects, such as XDocument, XElement, and
XAttribute to represent parts of an XML document.

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

In this very first post I will look at how to "Read from an XML document using LINQ to XML"

But before we proceed we must have an xml document to query. Please note that we are going to use the following xml document in all our examples. I have named it students.xml.

<?xml version="1.0" encoding="utf-8" ?>

      <Seminar Type="Blended-Learning">Maths</Seminar>
        <Seminar Type="E-Learning">Office 2010</Seminar>
            <Street>Kosti Palama</Street>
    <Seminar Type="Blended-Learning">Physics</Seminar>
      <Seminar Type="E-Learning">ASP.Net</Seminar>
            <Street>Ormond street</Street>

    <Seminar Type="E-Learning">
      <Seminar Type="Blended-Learning">Chemistry</Seminar>
            <Street>Messsina road 12</Street>

        <Seminar Type="E-Learning">English</Seminar>
        <Seminar Type="Blended-Learning">WPF</Seminar>
            <Street>Mopipetro 32</Street>



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

2) Add an new XML file to your site. Name it students.xml and just paste in it the xml code above.

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 students = xelement.Elements();
        // Read the entire XML
        foreach (var student in students)



We use the XElement.Load method to create a new XElement from a file specified in the path. Then we store in a variable the collection of the child elements.

Then we just iterate through the elements. It is quite clear that we are only interested in the Name and StudentId values of all students in the XML doc.

4)  Run your application and see in the browser the following results.


I will continue with more posts on LINQ to XML.Hope it helps!!!

No Comments