开发者

Convert a dictionary<string,string> to xml

开发者 https://www.devze.com 2022-12-13 11:55 出处:网络
I want to convert a dictionary<string,string> to this xml: <root> <key>value</key>

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>
0

精彩评论

暂无评论...
验证码 换一张
取 消