如何将Dictionary <string,object =“”>序列化/反序列化为XML </string,>

时间:2014-04-08 11:49:41

标签: c# xml

我正在尝试为我的应用程序编写一个保存例程,其中应用程序的几个部分将项添加到Dictionary,然后save函数将它们写入XML文件。打开例程需要读取这些文件并重新填充Dictionary,然后我可以将这些对象放回我的应用程序中。我正在努力解决我现在的例程的反序列化问题。我的保存程序如下

XmlDocument xmlDoc = new XmlDocument();

// Write down the XML declaration
XmlDeclaration xmlDeclaration = xmlDoc.CreateXmlDeclaration("1.0", "utf-8", null);

// Create the root element
XmlElement rootNode = xmlDoc.CreateElement("TireStudy");
xmlDoc.InsertBefore(xmlDeclaration, xmlDoc.DocumentElement);
xmlDoc.AppendChild(rootNode);

foreach (var saveItem in _SaveItems)
{
    XPathNavigator nav = rootNode.CreateNavigator();
    using (var writer = nav.AppendChild())
    {
        var serializer = new XmlSerializer(saveItem.Value.GetType());
        writer.WriteWhitespace("");
        serializer.Serialize(writer, saveItem.Value);
        writer.Close();
    }
}

xmlDoc.Save(fileName);

此例程用于创建文件,但我希望字典的键值也保存在文件中,我不知道如何反序列化这个创建的文件因为我不知道类型在我阅读它们之前的对象。

第2部分(我讨厌在问题中添加新部分,但我没有看到解决问题的更好方法)

我现在有以下代码,

var knownTypes = new List<Type>
{
   typeof(ObservableCollection<string>), 
   typeof(ObservableCollection<Segments>),
   typeof(Segments),
   typeof(List<string>)
};
var serialized = _SaveItems.Serialize(knownTypes);

但我得到以下异常

Type 'System.Collections.Generic.List`1[System.String]' cannot be added to list of known types since another type 'System.Collections.ObjectModel.ObservableCollection`1[System.String]' with the same data contract name 'http://schemas.microsoft.com/2003/10/Serialization/Arrays:ArrayOfstring' is already present. If there are different collections of a particular type - for example, List<Test> and Test[], they cannot both be added as known types.  Consider specifying only one of these types for addition to the known types list.

如果删除typeof(ObservableCollection)或typeof(List),则异常抱怨它需要我删除的那个。

1 个答案:

答案 0 :(得分:3)

您可以按照此post中的说明使用DataContractSerializer,但您可能必须将已知类型作为参数传递给序列化程序,以支持嵌套的object类型类:

using System;
using System.Collections.Generic;
using System.Runtime.Serialization;
using System.IO;
using System.Xml;

public static class SerializationExtensions
{
    public static string Serialize<T>(this T obj, IEnumerable<Type> knownTypes)
    {
        var serializer = new DataContractSerializer(obj.GetType(), knownTypes);
        using (var writer = new StringWriter())
        using (var stm = new XmlTextWriter(writer))
        {
            serializer.WriteObject(stm, obj);
            return writer.ToString();
        }
    }
    public static T Deserialize<T>(this string serialized, IEnumerable<Type> knownTypes)
    {
        var serializer = new DataContractSerializer(typeof(T), knownTypes);
        using (var reader = new StringReader(serialized))
        using (var stm = new XmlTextReader(reader))
        {
            return (T)serializer.ReadObject(stm);
        }
    }
}

public class Address
{
    public string Country { get; set; }
    public string City { get; set; }
}
public class CodedAddress
{
    public int CountryCode { get; set; }
    public int CityCode { get; set; }
}
class Program
{
    static void Main(string[] args)
    {
        var persons1 = new Dictionary<string, Address>();
        persons1.Add("John Smith", new Address { Country = "US", City = "New York" });
        persons1.Add("Jean Martin", new Address { Country = "France", City = "Paris" });

        // no need to provide known types to the serializer
        var serializedPersons1 = persons1.Serialize(null);
        var deserializedPersons1 = serializedPersons1.Deserialize<Dictionary<string, Address>>(null);


        var persons2 = new Dictionary<string, object>();
        persons2.Add("John Smith", new Address { Country = "US", City = "New York" });
        persons2.Add("Jean Martin", new CodedAddress { CountryCode = 33, CityCode = 75 });

        // must provide known types to the serializer
        var knownTypes = new List<Type> { typeof(Address), typeof(CodedAddress) };
        var serializedPersons2 = persons2.Serialize(knownTypes);
        var deserializedPersons2 = serializedPersons2.Deserialize<Dictionary<string, object>>(knownTypes);
    }
}