The LINQ project is part of the Microsoft.NET C# 3.0 framework. LINQ allows the developer to manipulate the data in both the memory and persistent data store. In this article I will introduce the XLINQ API which is used to manipulate the XML structured documents.

Introduction:

 

The LINQ project is part of the Microsoft.NET C# 3.0 framework. LINQ allows the developer to manipulate the data in both the memory and persistent data store. In this article I will introduce the XLINQ API which is used to manipulate the XML structured documents.

 

Installing LINQ Preview May CTP 2006:

 

If you are running Visual Studio.NET 2005 then you can download the LINQ Preview May CTP 2006 using the following URL:

 

LINQ Preview May CTP 2006

 

CAUTION: Your intellisense in Visual Studio.NET 2005 may behave in strange ways. Also the smart tag will not work after installing LINQ May CTP 2006.

 

Installing LINQ Using Visual Web Developer Orcas Express Edition:

 

A safer approach is to download and install the Visual Web Developer Orcas Express Edition. It is only 40 MB in size and the intellisense stays intact. You can download the Visual Web Developer Orcas Express Edition using the following URL:

 

Visual Web Developer Orcas Express Edition

 

Consuming Rss Feeds Using XLINQ:

 

Now, we are ready to get our hands dirty with XLINQ. In the first example I am going to create a very simple page that consumes and displays the RSS feeds. The first task is to make a reference to the System.Xml.XLinq assembly and include the System.Xml.XLinq namespace. Let’s see the complete code and then I will explain it bit by bit.

 

private void ConsumeRssFeeds()

    {

        string url = "http://aspadvice.com/blogs/azamsharp/rss.aspx";

       

        XElement feeds = XElement.Load(url);

       

        if(feeds.Element("channel") != null)

        {

            dlFeeds.DataSource = from f in feeds.Element("channel").Elements("item").Take(15)

                                select new { Title = f.Element("title").Value , Link = f.Element("link").Value };

                               

                                dlFeeds.DataBind();

        }

     

 

The first line in the ConsumeRssFeeds method declares “url” variable of type string which is used to hold the path to the rss feeds. The XElement.Load is used to load the Xml from the url and put it inside the feeds variable of type XElement.

 

After that I make sure that the feeds contain the “channel” element. The heart of the application is the following query:

 

from f in feeds.Element("channel").Elements("item").Take(15)

                                select new { Title = f.Element("title").Value , Link = f.Element("link").Value };

 

 

The above query can be read as follows:

 

Select 5 feeds from the feeds item element and make a new object with two properties having Title equals to feed title and Link equals to feed link.

 

And finally, the returned IEnumerable<XElement> is assigned to the DataList control which displays the feed.

 

   <asp:DataList ID="dlFeeds" runat="server">

    <ItemTemplate>

    <asp:HyperLink ID="linkFeed" runat="server" Text = '<%# Eval("Title") %>' NavigateUrl='<%# Eval("Link") %>' />

    </ItemTemplate>

   

    </asp:DataList>

 

 

 

Reading an XML File:

 

For this and later demos I will be using a Console Application project. You can download the Microsoft Visual C# Codename Orcas Express Edition from the link provided at the top. This will allow you to create Windows and Console applications which use LINQ.

 

The XML File:

 

The XML file is very simple. Take a look at the XML file below:

 

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

<Books>

  <Book>

    <ID>1</ID>

    <Name>Foundations of Atlas</Name>

    <Author>AJ</Author>

  </Book>

  <Book>

    <ID>2</ID>

    <Name>ASP.NET Programming</Name>

    <Author>Scott</Author>

  </Book>

</Books>

 

And here is the code to read the Book element from the XML file which has the ID = 1.

 

public static void ReadXmlFile()

        {

            string path = @"C:\Books.xml";

 

            XElement books = XElement.Load(path);

 

            if (books.Nodes().Count() > 0)

            {               

                var s = from b in books.Elements("Book")

                            where Int32.Parse(b.Element("ID").Value)==1

                            select b;

 

                foreach (XElement x in s)

                {

                    Console.WriteLine(x.Value);

                }

           

            }

        }

 

The code is pretty self explanatory. I am iterating through the Book elements and I only select the element if the ID element’s value is 1.

 

Creating Anonymous Type Objects Using XML File:

 

You can even create anonymous type objects based on the data from the XML file. Let’s check out a small example.

 

private static void CreatingObjectsFromXmlFile()

        {

            string path = @"C:\Books.xml";

 

            XElement books = XElement.Load(path);

 

            if (books.Nodes().Count() > 0)

            {

                var bookList = from b in books.Elements("Book")

                           select new { ID = b.Element("ID").Value, Name = b.Element("Name").Value, Author = b.Element("Author").Value };

 

                foreach (var book in bookList)

                {

                    Console.WriteLine(book.ID);

                    Console.WriteLine(book.Name);

                    Console.WriteLine(book.Author);

                }

            }

 

        }

 

Everything looks the same except the following clause:

 

select new { ID = b.Element("ID").Value, Name = b.Element("Name").Value, Author = b.Element("Author").Value };

 

The anonymous type allows you to create objects that do not belong to a named class. In the above code I am creating an object which consists of three properties namely ID, Name and Author. The compiler does not know the type of that object and neither do I. This is because it is an anonymous type object.

 

Creating a New Element in an XML File:

 

Creating a new element in an XML file is also simple operation.

 

private static void CreateNewBook()

        {

            string path = @"C:\Books.xml";

 

            XElement books = XElement.Load(path);

 

            XElement newBook = new XElement("Book");

            newBook.Add(new XElement("ID"));

            newBook.Element("ID").Value = "3";

            newBook.Add(new XElement("Name"));

            newBook.Element("Name").Value = "Johny Bravo Rules";

            newBook.Add(new XElement("Author"));

            newBook.Element("Author").Value = "Disney";

 

            books.Add(newBook);

            books.Save(path);         

          

        }

 

All you need to do is to add a new XElement object and when you are finished adding the children elements you can fire the Save method on the parent element.

 

Removing an Element By ID:

 

I am sure that there is a more suitable way to remove an element from the XML file based on the ID of the element. Here is what I come up with:

 

private static void RemovingBook(int bookID)

        {

            string path = @"C:\Books.xml";

 

            XElement books = XElement.Load(path);

 

            IEnumerable<XElement> elements = from b in books.Elements("Book")

                                             where Int32.Parse(b.Element("ID").Value) == bookID

                                             select b;

 

            foreach (var element in elements)

            {

                element.Remove();

            }

 

            books.Save(path);       

        }

 

Conclusion:

 

The LINQ project is the future of data access in the .NET framework. The API provides an easy access to manipulate the data stored in different sources. In the later articles I will talk about DLINQ project which is used to perform Database manipulation using LINQ queries.

 

I hope you enjoyed the article, happy coding!