views:

103

answers:

1

I want to convert a dictionary<string,string> to this xml:

<root>
    <key>value</key>
    <key2>value2</key2>
</root>

Can this be done using some fancy linq?

+3  A: 

No need to even get particularly fancy:

var xdoc = new XDocument(new XElement("root",
       dictionary.Select(entry => new XElement(entry.Key, entry.Value))));

Complete example:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Xml.Linq;

class Test
{
    static void Main()
    {
        var dictionary = new Dictionary<string, string>
        {
            { "key", "value" },
            { "key2", "value2" }
        };

        var xdoc = new XDocument(new XElement("root",
            dictionary.Select(entry => new XElement(entry.Key, entry.Value))));

        Console.WriteLine(xdoc);
    }
}

Output:

<root>
  <key>value</key>
  <key2>value2</key2>
</root>
Jon Skeet
did you do this on your phone? :)
mrblah