将字典<string,string>转换为xml </string,string>

时间:2009-12-01 21:06:13

标签: xml linq dictionary

我想转换字典&lt; string,string&gt;这个xml:

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

这可以使用一些花哨的linq来完成吗?

1 个答案:

答案 0 :(得分:4)

甚至不需要特别花哨:

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

完整示例:

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

输出:

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