【发布时间】:2015-08-11 16:20:29
【问题描述】:
我正在尝试反序列化一个我也在另一个时间序列化的 XML 文档。我正在使用它来存储配置文件。
这是我的代码:
namespace OrderTracker
{
[Serializable]
public class AutofillValues
{
private string fileName = Directory.GetCurrentDirectory() + "\\bin\\settings.db";
public ComboBox.ObjectCollection Vendors { get; set; }
public ComboBox.ObjectCollection Products { get; set; }
public ComboBox.ObjectCollection Companies { get; set; }
public void save(AutofillValues afv)
{
if (!File.Exists(fileName))
{
FileStream fs = File.Create(fileName);
fs.Close();
}
XmlSerializer x = new XmlSerializer(typeof(AutofillValues));
TextWriter writer = new StreamWriter(fileName);
x.Serialize(writer, afv);
writer.Close();
}
public AutofillValues load()
{
XmlSerializer x = new XmlSerializer(typeof(AutofillValues));
TextReader file = new StreamReader(fileName);
AutofillValues av = (AutofillValues)x.Deserialize(file);
file.Close();
return av;
}
}
}
我在尝试反序列化文件时收到的错误消息是这样的;
System.Xml.dll 中出现“System.InvalidOperationException”类型的未处理异常 附加信息:XML 文档中存在错误 (2, 2)。*
这是 XML 文档:
<?xml version="1.0" encoding="utf-8"?>
<AutofillValues xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<Vendors>
<anyType xsi:type="xsd:string">Test Vendor</anyType>
</Vendors>
<Products>
<anyType xsi:type="xsd:string">Test Product</anyType>
</Products>
<Companies>
<anyType xsi:type="xsd:string">Test Company</anyType>
</Companies>
</AutofillValues>
如何反序列化 XML 文件并取回序列化数据?
【问题讨论】:
-
您不能将其反序列化 - 这是 XmlSerializer 的限制,如 SO post 中所述。
-
忘了提——问题是
ComboBox.ObjectCollection没有无参数构造函数——XmlSerializer 需要一个没有参数的默认构造函数!
标签: c# xml serialization deserialization