2013-02-17 79 views
0

希望我可以问一些帮助序列化字典到一个Xml文件。推出序列化字典

我从数据库中提取数据,它显示如下,并希望在一个Xml文件中。

enter image description here

这是我的类(对象),我打算用作为方法序列化列表作为序列化一起。

public class Product 
{ 
    static public void SerializeToXMLCollection(List<Product> products) 
    { 
     XmlSerializer serializer = new XmlSerializer(typeof(List<Product>)); 
     string path = string.Concat(Environment.CurrentDirectory, "../../Products.xml"); 
     TextWriter textWriter = new StreamWriter(path); 
     serializer.Serialize(textWriter, products); 
     textWriter.Close(); 
    } 

    public Guid guid 
    { 
     get; 
     set; 
    } 


    public Dictionary<string, List<string>> MyDictionary 
    { 
     get; 
     set; 
    } 

这是我用添加的每个产品实例

List<Product> products = new List<Product>(); 

while (dbread.Read()) 
     { 

      Product p = new Product(); 

      string code = (string)dbread["ProdId"]; 
      string Subject = (string)dbread["Subject"]; 
      string GeneralSubject = (string)dbread["GeneralSubject"]; 
      p.guid = Guid.NewGuid(); 

      if (dict.ContainsKey(code)) 
      { 
       dict[code].Add(Subject); 


      } 
      else 
      { 

       dict.Add(code, new List<string> { Subject, GeneralSubject}); 

      } 
      //I assign the dict object to myDictionary in the Product class 
      p.MyDictionary = dict; 
      //now I add the entire object to List<Product> products so as to serialize this list 
      products.Add(p); 

最后我尝试序列名单

Product.SerializeToXMLCollection(products); 

列表一起查询,但我得到一个InvalidOperationException。

如何序列化此对象?我认为问题可能在于对象包含字典。

回答