48

只是好奇为什么 Dictionary 不受支持XmlSerializer

您可以通过使用DataContractSerializer对象并将其写入 a来轻松解决它XmlTextWriter,但是考虑到它实际上是一个 KeyValuePairs 数组,字典的哪些特征使得 a 难以XmlSerializer处理。

实际上,您可以将 an 传递IDictionary<TKey, TItem>给期望IEnumerable<KeyValuePairs<TKey, ITem>>.

4

3 回答 3

32

哈希表通常需要哈希码和相等比较器提供程序。这些不能在 XML 中轻松序列化,而且绝对不能移植。

但我想你已经找到了答案。只需将哈希表序列化为 aList<KeyValuePair<K,V>>然后(重新)将其构造为哈希表。

于 2010-05-26T09:18:12.537 回答
7

这已经很晚了 - 但我在自己寻找答案时发现了这个问题,并认为我会分享我的最终答案,该答案将替换XmlSerializer为可以序列化所有内容的不同工具:

http://www.sharpserializer.com

它直接开箱即用,序列化字典和多层自定义类型,甚至使用接口作为类型参数的泛型。还具有完全许可的许可证。

谢谢帕维尔·伊兹科夫斯基!

于 2011-09-22T22:40:33.013 回答
3

您可以使用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>

您可以从nuget安装 ExtendedXmlSerializer或运行以下命令:

Install-Package ExtendedXmlSerializer
于 2016-09-22T13:20:56.780 回答