希望我能帮助将字典序列化为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。
如何序列化此对象?我认为问题可能是该对象包含字典。
答案 0 :(得分:1)
我相信DataContractSerializer支持Dictionary对象。我甚至记得在某些时候使用它,但似乎无法找到我自己的任何例子。
但是在官方文档页面上有一些示例:http://msdn.microsoft.com/en-us/library/system.runtime.serialization.datacontractserializer.aspx
否则,您可能需要使用支持XML序列化的替换Dictionary类,例如http://weblogs.asp.net/pwelter34/archive/2006/05/03/444961.aspx