C# 无法从字典创建xml文件
我正在使用这个类C# 无法从字典创建xml文件,c#,xml,list,dictionary,C#,Xml,List,Dictionary,我正在使用这个类 public class Branch { public string Name { get; set; } public User Manager { get; set; } public User Secretary { get; set; } public Dictionary<string, User> Broker; public Dictionary<string, Apartment> Apartm
public class Branch
{
public string Name { get; set; }
public User Manager { get; set; }
public User Secretary { get; set; }
public Dictionary<string, User> Broker;
public Dictionary<string, Apartment> Apartments;
public Branch()
{}
public Branch(Branch other)
{
Name = other.Name;
Manager = other.Manager;
Secretary = other.Secretary;
Broker = other.Broker;
Apartments = other.Apartments;
}
}
当程序到达save\u branch2xml
方法中的XmlSerializer
行时,程序将崩溃。请参见此线程
如果你真的愿意,你可以使用SerializableDictionary。XmlSerializer不支持字典,我认为这些年来它都没有改变。有多种变通方法,可以推荐其中两种 首先,将内部数据结构更改为可序列化的数据结构。一份成对的清单就行了 其次,使用
DataContractSerializer
而不是xml序列化程序。数据协定序列化程序支持字典的序列化。您所说的“程序崩溃”是什么意思?我猜您的意思是抛出了异常-在这种情况下,您应该给出异常的详细信息。
static public void Save_Branch2XML(Dictionary<string, Branch> D)
{
//List<KeyValuePair<string, User>> DictionList = D.ToList();
List<Branch> DictionList = D.Select(p => new Branch(p.Value)).ToList<Branch>();
XmlSerializer Serializer = new XmlSerializer(DictionList.GetType());
TextWriter writer = new StreamWriter(@"C:\Users\tzach_000\Documents\Visual Studio 2013\Projects\RealEstate\RealEstate\DB\XMLBranch.xml");
Serializer.Serialize(writer, DictionList);
writer.Close();
}