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?
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>
精彩评论