0
希望我可以問一些幫助序列化字典到一個Xml文件。推出序列化字典
我從數據庫中提取數據,它顯示如下,並希望在一個Xml文件中。
這是我的類(對象),我打算用作爲方法序列化列表作爲序列化一起。
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。
如何序列化此對象?我認爲問題可能在於對象包含字典。