XML序列化字典

问题描述:

我想序列化字典集合,但我的代码有错误。我错在哪里? 这是我的代码。XML序列化字典

Dictionary<country,string> Countries=new Dictionary<country,string>(); 

Countries.Add(new country() { code = "AF", iso = 4 }, "Afghanistan"); 
Countries.Add(new country() { code = "AL", iso = 8 }, "Albania"); 
Countries.Add(new country() { code = "DZ", iso = 12 }, "Algeria"); 
Countries.Add(new country() { code = "AD", iso = 20 }, "Andorra"); 

FileStream fs = new FileStream("John1.xml", FileMode.Create); 
XmlSerializer xs = new XmlSerializer(typeof(Dictionary<country, string>)); 
xs.Serialize(fs, Countries); 

类国家

public class country 
{ 
    public string code { get; set; } 
    public int iso { get; set; } 
} 
+5

'XmlSerializer'不适用于字典。尝试制作一个'List >'。 – Romoku

+0

@Romoku实际上'System.Collections.Generic.KeyValuePair'是不可序列化的,所以你不能使用它。 – Alberto

+0

是的,我通常做结构或使用'Tuple'。 – Romoku

你可以用DataContractSerializer选项去。它可以序列化.NET字典

How to: Serialize Using DataContractSerializer

的XmlSerializer无法序列一本字典,但你可以改变你的字典中的键值对的列表和序列化:

Dictionary<country,string> Countries=new Dictionary<country,string>(); 

Countries.Add(new country() { code = "AF", iso = 4 }, "Afghanistan"); 
Countries.Add(new country() { code = "AL", iso = 8 }, "Albania"); 
Countries.Add(new country() { code = "DZ", iso = 12 }, "Algeria"); 
Countries.Add(new country() { code = "AD", iso = 20 }, "Andorra"); 

FileStream fs = new FileStream("John1.xml", FileMode.Create); 
XmlSerializer xs = new XmlSerializer(typeof(List<KeyValuePair<country, string>>)); 
xs.Serialize(fs, Countries.Select(x=>new KeyValuePair<country,string>(){ Key = x.Key, Value = x.Value}).ToList()); 

编辑: 另一件事考虑到:您不能使用框架提供的System.Collections.Generic.KeyValuePair结构,因为它不可序列化(Key和Value属性标记为只读)。您必须编写自己的KeyValue结构:

[Serializable] 
public struct KeyValuePair<K, V> 
{ 
    public K Key { get; set; }  
    public V Value { get; set; } 
} 
+0

感谢阿尔贝托,我使用它。 – johny