Using LINQ to represent XML data as an Object containing Master-Detail records

Posted by: Suprotim Agarwal , on 4/7/2010, in Category LINQ
Views: 97974
Abstract: : In this article, we will read an XML file containing Master-Detail records and represent it as an object using LINQ.
Using LINQ to represent XML data as an Object containing Master-Detail records
 
In this article, we will read an XML file containing Master-Detail records and represent it as an object using LINQ. This solution is based on a solution shared earlier by Samuel.
I assume that you are familiar with LINQ to XML. If not, I would recommend you to get some hands-on on LINQ to XML to check out how to traverse nodes. These three articles will help you out:
Here’s the sample XML file called CountryState.xml that we will be reading. As you can see, one Country has multiple State nodes in it.
<Countries>
    <Country>
        <CID>1</CID>
        <CountryName>India</CountryName>
        <States>
            <State>
                New Delhi
            </State>
            <State>
                Maharashtra
            </State>
            <State>
                Rajasthan
            </State>
        </States>
    </Country>
 
    <Country>
        <CID>2</CID>
        <CountryName>United States</CountryName>
        <States>
            <State>
                Washington
            </State>
            <State>
                Texas
            </State>
        </States>
    </Country>
 
    <Country>
        <CID>3</CID>
        <CountryName>Australia</CountryName>
        <States>
            <State>
                Queensland 
            </State>
            <State>
                Victoria
            </State>
        </States>
    </Country>
</Countries>
Let’s see the steps to read this XML file and represent it as an object. The code is easy to follow, so I won’t really be explaining every bit of it. Check the LINQ to XML series link I posted earlier if you are new to LINQ.
Let’s get started! Create a Console Application and add a class called ‘Country’ to it.
C#
using System.Collections.Generic;
 
namespace ReadXMLSiteMapIntoObject
{
    class Country
    {
        public string countryName { get; set; }
        public IList<States> states = new List<States>();
    }
 
    class States
    {
        public string stateName { get; set; }
    }
 
}
 
VB.NET
Imports System.Collections.Generic
 
Namespace ReadXMLSiteMapIntoObject
      Friend Class Country
            Private privatecountryName As String
            Public Property countryName() As String
                  Get
                        Return privatecountryName
                  End Get
                  Set(ByVal value As String)
                        privatecountryName = value
                  End Set
            End Property
            Public states As IList(Of States) = New List(Of States)()
      End Class
 
      Friend Class States
            Private privatestateName As String
            Public Property stateName() As String
                  Get
                        Return privatestateName
                  End Get
                  Set(ByVal value As String)
                        privatestateName = value
                  End Set
            End Property
      End Class
 
End Namespace
 
As you can see, the class Country contains a field ‘states’ of type IList<States>.
Now write code to read the XML file and populate a List<Country> as shown below:
C#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Xml.Linq;
 
namespace ReadXMLSiteMapIntoObject
{
class Program
{
static void Main(string[] args)
{
XDocument xdoc = XDocument.Load("../../CountryState.xml");
List<Country> countries = (from cntry in xdoc.Element("Countries").Elements("Country")
               select new Country
               {
                   countryName = cntry.Element("CountryName").Value,
                   states = (from ste in cntry.Element("States").Elements("State")
                             select new States
                             {
                                 stateName = ste.Value
                             }).ToList()
               }).ToList();
 
 
    foreach (var co in countries)
    {
         Console.WriteLine(co.countryName);
        foreach (var st in co.states)
        {
            Console.WriteLine(st.stateName);
        }
}
 
Console.ReadLine();
}
}
}
VB.NET
Imports System
Imports System.Collections.Generic
Imports System.Linq
Imports System.Xml.Linq
 
Namespace ReadXMLSiteMapIntoObject
Friend Class Program
Shared Sub Main(ByVal args() As String)
Dim xdoc As XDocument = XDocument.Load("../../CountryState.xml")
Dim countries As List(Of Country) = ( _
    From cntry In xdoc.Element("Countries").Elements("Country") _
    Select New Country With {.countryName = cntry.Element("CountryName").Value, .states = ( _
            From ste In cntry.Element("States").Elements("State") _
            Select New States With {.stateName = ste.Value}).ToList()}).ToList()
 
 
      For Each co In countries
             Console.WriteLine(co.countryName)
            For Each st In co.states
                  Console.WriteLine(st.stateName)
            Next st
      Next co
 
Console.ReadLine()
End Sub
End Class
End Namespace
 
In the code shown above, we use the XDocument.Load() to read the XML file and populate a List<Country> by traversing the Countries > Country nodes and then populate the states property by traversing the States > State nodes.
We then loop through the countries collection and print the name of the country and the states within it. Remember that the class Country holds a variable of type IList<States>
That’s it. When you run the code, you should get a similar output
Output
I hope this article was useful and I thank you for viewing it. The entire source code of this article can be downloaded over here
If you liked the article,  Subscribe to the RSS Feed or Subscribe Via Email

This article has been editorially reviewed by Suprotim Agarwal.

Absolutely Awesome Book on C# and .NET

C# and .NET have been around for a very long time, but their constant growth means there’s always more to learn.

We at DotNetCurry are very excited to announce The Absolutely Awesome Book on C# and .NET. This is a 500 pages concise technical eBook available in PDF, ePub (iPad), and Mobi (Kindle).

Organized around concepts, this Book aims to provide a concise, yet solid foundation in C# and .NET, covering C# 6.0, C# 7.0 and .NET Core, with chapters on the latest .NET Core 3.0, .NET Standard and C# 8.0 (final release) too. Use these concepts to deepen your existing knowledge of C# and .NET, to have a solid grasp of the latest in C# and .NET OR to crack your next .NET Interview.

Click here to Explore the Table of Contents or Download Sample Chapters!

What Others Are Reading!
Was this article worth reading? Share it with fellow developers too. Thanks!
Share on LinkedIn
Share on Google+

Author
Suprotim Agarwal, MCSD, MCAD, MCDBA, MCSE, is the founder of DotNetCurry, DNC Magazine for Developers, SQLServerCurry and DevCurry. He has also authored a couple of books 51 Recipes using jQuery with ASP.NET Controls and The Absolutely Awesome jQuery CookBook.

Suprotim has received the prestigious Microsoft MVP award for Sixteen consecutive years. In a professional capacity, he is the CEO of A2Z Knowledge Visuals Pvt Ltd, a digital group that offers Digital Marketing and Branding services to businesses, both in a start-up and enterprise environment.

Get in touch with him on Twitter @suprotimagarwal or at LinkedIn



Page copy protected against web site content infringement 	by Copyscape




Feedback - Leave us some adulation, criticism and everything in between!
Comment posted by alena on Monday, May 10, 2010 4:35 AM
<p><strong><a href="http://www.bag-salon.com/lv-c-12.html?zenid=ee41af4987e2624bf23dafb977a7e707" target="_blank">Louis Vuitton Bags</a></strong>: A Fashion Genre! Among all brands of<strong> <a href="www.bag-salon.com" target="_blank">handbags</a></strong> that are currently  available in the market, one brand name that mostly catches women's attention  is <a href="http://www.bag-salon.com/lv-c-12.html?zenid=ee41af4987e2624bf23dafb977a7e707">Louis Vuitton</a> . No woman can deny this fact, since its classic design and  distinct color always come in style and fashion.<strong> <a href="www.bag-salon.com">Louis Vuitton</a></strong> bags are considered as every woman's  dream to own. All<a href="http://www.bag-salon.com/lv-c-12.html?zenid=ee41af4987e2624bf23dafb977a7e707"> LV Bags</a> are made with high quality material. With LV  handbags, it is suitable for you to go shopping or dating, which will make you  charming and elegant. Here has<strong><a href="www.bag-salon.com"> LV e-store</a></strong> which will fulfill your dream at an affordable price. Just browsing our page,  you will find your ideal handbags to fit your every occasion. </p>
Comment posted by shirley on Monday, May 10, 2010 4:37 AM
http://www.bag-salon.com
Louis Vuitton Bags: A Fashion Genre! Among all brands of handbags that are currently available in the market, one brand name that mostly catches women's attention is Louis Vuitton . No woman can deny this fact, since its classic design and distinct color always come in style and fashion. Louis Vuitton bags are considered as every woman's dream to own. All LV Bags are made with high quality material. With LV handbags, it is suitable for you to go shopping or dating, which will make you charming and elegant. Here has LV e-store which will fulfill your dream at an affordable price. Just browsing our page, you will find your ideal handbags to fit your every occasion.
Comment posted by Lino on Thursday, June 13, 2013 7:34 AM
Http://www.custodiestensi.it
Very beautifile Article.
Comment posted by Lino on Thursday, June 13, 2013 7:36 AM
<a href="http://www.custodiestensi.it" target="_blank">Beautiful</a>
Comment posted by Lino on Thursday, June 13, 2013 7:36 AM
<a href="http://www.custodiestensi.it" target="_blank">Beautiful</a>