SIGN UP MEMBER LOGIN:    
ARTICLE

Reading XML File Through LINQ: A Few Tips

Posted by Dhananjay Kumar Articles | XML in C# June 20, 2011
In this articlet I will discuss how to read XML files using LINQ. We will see some tips as well.
Reader Level:


In this articlet I will discuss how to read XML files using LINQ. We will see some tips as well.

Let us say we have a XML file as below; the file is stored on the D drive. The XML file contains information about books.

Data.Xml

<?xml version="1.0" encoding="utf-8" ?>
<catalog>
  <books>
<book id="bk101"
  <author id="1">Gambardella, Matthew</author>
  <title>XML Developer's Guide</title>
  <genre>Computer</genre>
  <price>44.95</price>
  <publish_date>2000-10-01</publish_date>
   <description> An in-depth look at creating applications with XML.</description>
</book>
<book id="bk102">
  <author id="2">Ralls, Kim</author>
  <title>Midnight Rain</title>
  <genre>Fantasy</genre>
  <price>5.95</price>
  <publish_date>2000-12-16</publish_date>
  <description> A former architect battles corporate zombies,an evil sorceress, and her own childhood to become
queen of the world.</description>
</book>
<book id="bk103">
  <author id="3">Corets, Eva</author>
  <title>Maeve Ascendant</title>
  <genre>Fantasy</genre>
    <price>5.95</price>
    <publish_date>2000-11-17</publish_date>
    <description>After the collapse of a nanotechnology society in England, the young survivors lay the foundation for
a new society. </description>
  </book>
 
<book id="bk104">
    <author id="4">Corets, Eva</author>
    <title>Oberon's Legacy</title>
    <genre>Fantasy</genre>
    <price>5.95</price>
    <publish_date>2001-03-10</publish_date>
    <description>In post-apocalypse England, the mysterious agent known only as Oberon helps to create a new life for
 the inhabitants of London. Sequel to Maeve Ascendant.</description>
 
  </book>
 
<book id="bk105">
    <author id="5">Corets, Eva</author>
    <title>The Sundered Grail</title>
    <genre>Fantasy</genre>
    <price>5.95</price>
    <publish_date>2001-09-10</publish_date>
    <description>The two daughters of Maeve, half-sisters, battle one another for control of England. Sequel to
Oberon's Legacy.</description>
 
  </book>
  </books>
</catalog>


Fetching all the Books

To fetch all the books, we just need to parse the XML file. Find the descendants book and fetch it into an anonymous class.

ReadingXML1.gif

Fetching a Particular Book

If you want to fetch a particular book, we need to apply a where condition while parsing the XML file.

ReadingXML1.2.gif


Fetching the Attribute Value of a particular Book

Imagine you need to fetch the author Id of the book with Id bk102. To do that you need to select as below:

ReadingXML2.gif

Fetching all the Authors Name only

To fetch the entire author name, we need to execute the following query.

ReadingXML3.gif

For your reference thefull source code is as below:

Program.cs

using System;
using System.Linq;
using System.Xml.Linq;

namespace ConsoleApplication23
{
    class Program
    {
        static void Main(string[] args)
        {
            XDocument document = XDocument.Load("D:\\Data.xml");
            #region Fetch All the Books 
            var books = from r in document.Descendants("book")
                        select new
                            {
                                Author = r.Element("author").Value,
                                Title = r.Element("title").Value,
                                Genere = r.Element("genre").Value,
                                Price = r.Element("price").Value,
                                PublishDate = r.Element("publish_date").Value,
                                Description = r.Element("description").Value,
 
                            };
 
            foreach (var r in books)
            {
                Console.WriteLine(r.PublishDate + r.Title + r.Author);
            }
 
            Console.ReadKey(true);
            #endregion 
 
            #region Fetching a particular  Book            
            var selectedBook = from r in document.Descendants("book").Where
                                   (r=>(string)r.Attribute("id")=="bk102")
                        select new
                        {
                            Author = r.Element("author").Value,
                            Title = r.Element("title").Value,
                            Genere = r.Element("genre").Value,
                            Price = r.Element("price").Value,
                            PublishDate = r.Element("publish_date").Value,
                            Description = r.Element("description").Value,
 
                        };
 
            foreach (var r in selectedBook)
            {
                Console.WriteLine(r.PublishDate + r.Title + r.Author);
            }
            Console.ReadKey(true);
            #endregion 
 
          
 
            #region Fetching a particular  Book
 
          
            var selectedBookAttribute = (from r in document.Descendants("book").Where
                                        (r => (string)r.Attribute("id") == "bk102")
                                        select r.Element("author").Attribute("id").Value).FirstOrDefault();
            
            Console.WriteLine(selectedBookAttribute);         
                        
            Console.ReadKey(true);                                  
 
            #endregion
 
 
            #region Fetching all Authors 
 
           
            var allauthors = from r in document.Descendants("book")
                                         select r.Element("author").Value; 
            foreach(var r in allauthors)
            {
                Console.WriteLine(r.ToString());
            }
           
 
            Console.ReadKey(true);
 
            #endregion
 
 
     
 
        }
    }
}


Output

ReadingXML4.gif

I hope this article was useful. Thanks for reading.

Login to add your contents and source code to this article
share this article :
post comment
 
Team Foundation Server Hosting
Become a Sponsor
PREMIUM SPONSORS
  • Finally – a virtual platform that delivers next-generation Windows Server 2008 Hyper-V virtualization technology from a managed hosting partner you can truly depend on. Visit www.maximumasp.com/max for a FREE 30 day trial. Hurry offer ends soon. Climb aboard the MaxV platform and take advantage of High Availability, Intelligent Monitoring, Recurrent Backups, and Scalability – with no hassle or hidden fees. As a managed hosting partner focused solely on Microsoft technologies since 2000, MaximumASP is uniquely qualified to provide the superior support that our business is built on. Unparalleled expertise with Microsoft technologies lead to working directly with Microsoft as first to offer IIS 7 and SQL 2008 betas in a hosted environment; partnering in the Go Live Program for Hyper-V; and product co-launches built on WS 2008 with Hyper-V technology.
    Finally – a virtual platform that delivers next-generation Windows Server 2008 Hyper-V virtualization technology from a managed hosting partner you can truly depend on. Visit www.maximumasp.com/max for a FREE 30 day trial. Hurry offer ends soon. Climb aboard the MaxV platform and take advantage of High Availability, Intelligent Monitoring, Recurrent Backups, and Scalability – with no hassle or hidden fees. As a managed hosting partner focused solely on Microsoft technologies since 2000, MaximumASP is uniquely qualified to provide the superior support that our business is built on. Unparalleled expertise with Microsoft technologies lead to working directly with Microsoft as first to offer IIS 7 and SQL 2008 betas in a hosted environment; partnering in the Go Live Program for Hyper-V; and product co-launches built on WS 2008 with Hyper-V technology.
Nevron Gauge for SharePoint
Become a Sponsor