如何序列化词典<string,list <custom type =“”>&gt;到XML

时间:2016-05-30 12:54:34

标签: c# xml linq dictionary

我有一个自定义类:

public class DicExpense
{
    [XmlElement]
    public string EmployeeName { get; set; }

    [XmlElement]
    public string Company { get; set; }        
}

我将其放入这样的字典中:

  var dict = new Dictionary<string, List<DicExpense>>();
  dict.Add("Expense1",new List<DicExpense>())
  dict["Expense1"].Add(new DicExpense() {EmployeeName = "Sam", Comment = "something"})
  dict["Expense1"].Add(new DicExpense() {EmployeeName = "Sam", Comment = "something"})


  dict.Add("Expense2",new List<DicExpense>())
  dict["Expense2"].Add(new DicExpense() {EmployeeName = "John", Comment = "something"})
  dict["Expense2"].Add(new DicExpense() {EmployeeName = "John", Comment = "something"})

我想将其序列化为XML:

 <Expense>
 <key>Expense1</key>
 <EmployeeName>Sam</EmployeeName>
 <Comment>something</Comment>
 <EmployeeName>John</EmployeeName>
 <Comment>something</Comment>
 </Expense>

我正在尝试这个:

 StringBuilder output = new StringBuilder();
 var writer = new StringWriter(output);

 XmlSerializer serializer = new XmlSerializer(typeof(Dictionary<string,     List<DicExpense>>));
 serializer.Serialize(writer, records);
 Console.WriteLine(output);

但它不起作用。当您的值是自定义类型的集合时,有没有办法序列化它?

1 个答案:

答案 0 :(得分:0)

如果您要序列化/反序列化使用var isEmpty = !array[6].HasValue; 的类型,请使用Dictionary<TKey, TValue>

DataContractSerializer