Convert a generic List to XML file using XDocument

Niladri.Biswas
Posted by Niladri.Biswas under C# category on | Points: 40 | Views : 828
Given a collection of Countries

India
Bangaladesh
Singapore
Hongkong


The expected output is to create an XML file whose structure will be as

<CountryInfo>
<Countries>
<Country Name="India" />
<Country Name="Bangaladesh" />
<Country Name="Singapore" />
<Country Name="Hongkong" />
</Countries>
</CountryInfo>


Here is my solution

var countryList = new List() { "India", "Bangaladesh", "Singapore", "Hongkong" };
XDocument doc =
new XDocument
(
new XElement
(
"CountryInfo",
new XElement("Countries", countryList.Select(x => new XElement("Country", new XAttribute("Name", x))))
)
);
Console.WriteLine(doc.ToString());

Comments or Responses

Login to post response