Question: I have a dictionary with key value pair. I want to write it to XML using LINQ.

I am able to create the XML document using LINQ but not sure how to read the values from dictionary & write into the XML. 

Following is the example with hardcode values to generate XML, I want to ready the dictionary instead of hardcode values

```
XDocument doc = new XDocument(
    new XDeclaration("1.0", "utf-8", "true"),
    new XElement("countrylist",
        new XElement("country",
            new XAttribute("id", "EMP001"),
            new XAttribute("name", "EMP001")
        ),
        new XElement("country",
            new XAttribute("id", "EMP001"),
            new XAttribute("name", "EMP001")
        )
    )
);

```

Answer: 
If the id attribute is stored as dictionary key and the name as value, you can use the following

```
XDocument doc = new XDocument(
    new XDeclaration("1.0", "utf-8", "true"),
    new XElement("countrylist",
        dict.Select(d => new XElement("country",
            new XAttribute("id", d.Key),
            new XAttribute("name", d.Value))))
);

```
Assuming you have a `Country` class with an `Id` and a `Name` and the countries are stored as values in your dictionary *countries*, with the id beeing the key:

```
XDocument xDoc = new XDocument(new XDeclaration("1.0", "utf-8", "true"));
var xCountryList = new XElement("countrylist");
foreach(var kvp in countries)
    xCountryList.Add(new XElement("country",
        new XAttribute("id", kvp.Key),
        new XAttribute("name", kvp.Value.Name)));

```