反序列化xml文件时出现XamlParseException

时间:2013-12-10 18:07:16

标签: c# xml xml-parsing

我不会问,但我不知道什么是错的。我将车辆保存到xml文件中,当用户打开程序时我想反序列化。当我运行它时,我在加载方法的最后一行得到这个

   'System.Windows.Markup.XamlParseException' {"'The invocation of the constructor on type 'SD2CW2.MainWindow' that matches the specified binding constraints threw an exception.'} 

这些是我的加载/保存方法

    private void Load()
    {

        XmlSerializer SerializerObj = new XmlSerializer(typeof(Vechicle));

        // Reading a file requires a FileStream.
        FileStream fs = new FileStream(filepath);
        Vechicle = ((List<Vechicle>)SerializerObj.Deserialize(fs));
    }
    //Save the objects
    private void Save()
    {
        // Create a new file stream to write the serialized object to a file
        TextWriter WriteFileStream = new StreamWriter(filepath);

        Type [] extraTypes= new Type[2];
        extraTypes[0] = typeof(Tour);
        extraTypes[1] = typeof(Vechicle);
        // Create a new XmlSerializer instance with the type of List<Journey> and my addition types
        XmlSerializer SerializerObj = new XmlSerializer(typeof(List<Journey>),extraTypes);

        //serialising my journey list
        SerializerObj.Serialize(WriteFileStream,Journey);
        SerializerObj = new XmlSerializer(typeof(List<Vechicle>));
        //serialising my vechicle list
        SerializerObj.Serialize(WriteFileStream, Vechicle);
        // Cleanup
        WriteFileStream.Close();
    }

这个xml

<?xml version="1.0" encoding="utf-8"?>
<ArrayOfJourney xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" /><?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>1</Registration>
  </Vechicle>
  <Vechicle>
    <Id>2</Id>
    <Registration>2</Registration>
  </Vechicle>
  <Vechicle>
<Id>3</Id>
<Registration>3</Registration>

1 个答案:

答案 0 :(得分:1)

这是整个XML文件吗?因为它不完整。

如果是,请添加

</Vechicle>
</ArrayOfVechicle>
</ArrayOfJourney>

因此,您至少可以从一开始就获得格式良好的XML文档。