【问题标题】:Convert a dictionary<string,string> to xml将字典<string,string> 转换为 xml
【发布时间】:2009-12-01 21:06:13
【问题描述】:

我想将字典 转换成这个xml:

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

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

【问题讨论】:

    标签: xml linq dictionary


    【解决方案1】:

    甚至不需要特别花哨:

    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>
    

    【讨论】:

    • 您是在手机上执行此操作的吗? :)
    猜你喜欢
    • 2021-05-19
    • 1970-01-01
    • 2011-09-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-05-07
    • 1970-01-01
    • 2011-06-20
    相关资源
    最近更新 更多