我想转换字典< string,string>这个xml:
<root>
<key>value</key>
<key2>value2</key2>
</root>
这可以使用一些花哨的linq来完成吗?
答案 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>