Iv使用此方法序列化列表和列表以分隔xml文件。
private void Save(String filePath,Type saveType)
{
// Create a new file stream to write the serialized object to a file
TextWriter WriteFileStream = new StreamWriter(@filePath);
// Create a new XmlSerializer instance with the type of List<Journey> and my addition types
if (saveType == typeof(List<Vechicle>))
{
XmlSerializer SerializerObj = new XmlSerializer(saveType);
//serialising my vechicle list
SerializerObj.Serialize(WriteFileStream, Vechicle);
}
else
{
if (saveType == typeof(List<Journey>))
{
Type [] extraTypes= new Type[1];
extraTypes[0] = typeof(Tour);
XmlSerializer SerializerObj = new XmlSerializer(saveType,extraTypes);
SerializerObj.Serialize(WriteFileStream, Journey);
}
}
// Cleanup
WriteFileStream.Close();
}
这是vechicls xml文件的一个例子
<?xml version="1.0" encoding="utf-8"?>
<ArrayOfVechicle xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<Vechicle>
<Id>1</Id>
<Registration>a</Registration>
</Vechicle>
<Vechicle>
<Id>2</Id>
<Registration>b</Registration>
</Vechicle>
<Vechicle>
<Id>3</Id>
<Registration>c</Registration>
</Vechicle>
</ArrayOfVechicle>
当我尝试使用此方法将vechicle日期加载到我的列表中时出现问题
private void Load()
{
XmlSerializer SerializerObj = new XmlSerializer(typeof(Vechicle));
FileStream fs = new FileStream(filepath, FileMode.Open);
Vechicle = ((List<Vechicle>)SerializerObj.Deserialize(fs));
}
我在load方法的最后一行得到一个例外。 PresentationFramework.dll中出现'System.Windows.Markup.XamlParseException''类型'SD2CW2.MainWindow'上与指定绑定约束匹配的构造函数的调用引发异常。'
答案 0 :(得分:0)
您已序列化List<Vechicle>
,您应该反序列化相同的类型:
XmlSerializer SerializerObj = new XmlSerializer(typeof(List<Vechicle>));
FileStream fs = new FileStream(filepath, FileMode.Open);
var Vechicles = ((List<Vechicle>)SerializerObj.Deserialize(fs));
你看到XamlParseException beacuse serialize对于WPF至关重要的异常,它在XamlParseException
中包含了serializarion异常。您可以在XamlParseException实例的InnerException
属性中看到它。
但实际上在您的反序列化代码中,您应该处理List<Journey>
和List<Vechicle>
两种类型。由于您没有在文件中保存任何元数据(哪种类型已序列化),因此您的代码可能如下所示:
FileStream fs = new FileStream(filepath, FileMode.Open);
List<Vechicle> Vechicles = null;
List<Journey> Journeys = null;
try
{
XmlSerializer SerializerObj = new XmlSerializer(typeof(List<Vechicle>));
Vechicles = ((List<Vechicle>)SerializerObj.Deserialize(fs));
}
catch
{
Type [] extraTypes= new Type[] { typeof(Tour) };
XmlSerializer SerializerObj = new XmlSerializer(saveType, extraTypes);
Journeys = ((List<Journey>)SerializerObj.Deserialize(fs));
}
if ( Vechicles != null)
{
// do something
}
else if ( Journeys != null)
{
// do something
}
请注意,如果xmlserializer不对两种类型进行反序列化,则此处仍可能发生异常。