代码之家  ›  专栏  ›  技术社区  ›  theburningmonk

为什么XmlSerializer不支持字典?

  •  45
  • theburningmonk  · 技术社区  · 15 年前

    只是好奇为什么字典不支持 XmlSerializer

    你可以通过使用 DataContractSerializer 并将对象写入 XmlTextWriter 但是,词典的哪些特点让人难以理解呢 XmlSerializer 考虑到它实际上是一个KeyValuePairs数组。

    事实上,你可以通过考试 IDictionary<TKey, TItem> 对一个需要 IEnumerable<KeyValuePairs<TKey, ITem>> .

    3 回复  |  直到 15 年前
        1
  •  32
  •   leppie    15 年前

    哈希表通常需要哈希代码和相等比较器提供程序。这些不能在XML中很容易地序列化,而且肯定是不可移植的。

    但我想你已经找到了答案。只需将哈希表序列化为 List<KeyValuePair<K,V>>

        2
  •  7
  •   jv42    7 年前

    这太晚了-但我发现这个问题,同时寻找答案自己,并认为我会分享我的最终答案,这是取代 XmlSerializer 使用另一个将序列化所有内容的工具:

    http://www.sharpserializer.com

    对我来说,它直接起作用,序列化字典,多层自定义类型,甚至使用接口作为类型参数的泛型。也有完全许可证。

        3
  •  3
  •   Wojciech Nagórski    7 年前

    你可以用 ExtendedXmlSerializer 如果你有课:

    public class TestClass
    {
        public Dictionary<int, string> Dictionary { get; set; }
    }
    

    并创建此类的实例:

    var obj = new TestClass
    {
        Dictionary = new Dictionary<int, string>
        {
            {1, "First"},
            {2, "Second"},
            {3, "Other"},
        }
    };
    

    可以使用ExtendedXmlSerializer序列化此对象:

    var serializer = new ConfigurationContainer()
        .UseOptimizedNamespaces() //If you want to have all namespaces in root element
        .Create();
    
    var xml = serializer.Serialize(
        new XmlWriterSettings { Indent = true }, //If you want to formated xml
        obj);
    

    输出xml如下所示:

    <?xml version="1.0" encoding="utf-8"?>
    <TestClass xmlns:sys="https://extendedxmlserializer.github.io/system" xmlns:exs="https://extendedxmlserializer.github.io/v2" xmlns="clr-namespace:ExtendedXmlSerializer.Samples;assembly=ExtendedXmlSerializer.Samples">
      <Dictionary>
        <sys:Item>
          <Key>1</Key>
          <Value>First</Value>
        </sys:Item>
        <sys:Item>
          <Key>2</Key>
          <Value>Second</Value>
        </sys:Item>
        <sys:Item>
          <Key>3</Key>
          <Value>Other</Value>
        </sys:Item>
      </Dictionary>
    </TestClass>
    

    您可以从安装ExtendedXmlSerializer nuget

    Install-Package ExtendedXmlSerializer
    
    推荐文章