我的一个类能够在加载WPF应用程序后轻松地序列化和反序列化。我现在正试图在传入项目文件时添加在启动时加载项目的功能。不幸的是,它抛出了一个InvalidOperationException:
There is an error in XML document (2, 2). ---> System.InvalidOperationException: <WeightingParametersBit xmlns=''> was not expected.
WeightingParametersBit
是我尝试序列化的类的成员类型。它基本上只是一个Dictionary的容器。奇怪的是,该文件在文件中的任何位置都不包含<WeightingParametersBit xmlns=....
的标记。抛出此异常并启动应用程序。如果我单击加载按钮并选择相同的项目文件,它加载就好了。
这是我尝试序列化的类(小容器类):
public class WeightSettings
{
public double UserScoreSlagging;
public double UserScoreFouling;
public WeightMode BitWeightMode = WeightMode.Manual;
public WeightMode LigWeightMode = WeightMode.Manual;
public WeightingParametersBit BitWeights = new WeightingParametersBit();
public WeightingParametersLig LigWeights = new WeightingParametersLig();
}
这是它生成的xml(为了查看目的而裁剪):
<?xml version="1.0" encoding="utf-8"?>
<WeightSettings>
<UserScoreSlagging>0</UserScoreSlagging>
<UserScoreFouling>0</UserScoreFouling>
<BitWeightMode>Manual</BitWeightMode>
<LigWeightMode>Manual</LigWeightMode>
<BitWeights>
<bituminous>
...
</bituminous>
</BitWeights>
<LigWeights>
<lignitic>
...
</lignitic>
</LigWeights>
</WeightSettings>
我的通用序列化代码:
public static void Serialize<T>(this T source, TextWriter writer)
{
// Don't serialize a null object
if (Object.ReferenceEquals(source, null))
{
throw new ArgumentException("Trying to serialize null object.", "source");
}
XmlSerializer s = new XmlSerializer(typeof(T));
s.Serialize(writer, source);
writer.WriteLine();
}
反序列化代码:
public static T Deserialize<T>(this T source, TextReader reader)
{
XmlSerializer s = new XmlSerializer(typeof(T));
source = (T)s.Deserialize(reader);
return source;
}
对反序列化的调用来自名为WeightSettings
(类型为WeightSettings
)的属性,该属性不为空:
WeightSettings = WeightSettings.Deserialize(sr);
如何解决此问题?也许更重要的是:为什么我只在Window Loaded事件中看到这种行为?
答案 0 :(得分:0)
非常神秘的例外情况应该是FileNotFoundException