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))))
);

```
Here dude with the dictionary 

```
        Dictionary<int, string> fooDictionary = new Dictionary<int, string>();
        fooDictionary.Add(1, "foo");
        fooDictionary.Add(2, "bar");

        XDocument doc = new XDocument(
            new XDeclaration("1.0", "utf-8", "true"),
            new XElement("countrylist")
        );

        var countryList = doc.Descendants("countrylist").Single(); // Get Country List Element

        foreach (var bar in fooDictionary) {
            // Add values per item
            countryList.Add(new XElement("country",
                                new XAttribute("id", bar.Key),
                                new XAttribute("name", bar.Value)));
        }

```