Using LINQ to represent XML data as an Object containing Master-Detail records
Posted by: Suprotim Agarwal ,
on 4/7/2010,
in
Category LINQ
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
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
This article has been editorially reviewed by Suprotim Agarwal.
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!
Was this article worth reading? Share it with fellow developers too. Thanks!
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