Question

I'm trying to save two lists of my custom objects the first list of type List<Vechicle>.

XmlSerializer SerializerObjVechicle = new XmlSerializer(typeof(List<Vechicle>));

Then I get the error

"An unhandled exception of type 'System.Windows.Markup.XamlParseException' occurred in PresentationFramework.dll"

This is my vechicle class

[Serializable]
public class Vechicle
{

    private int _Id;
    private String _Registration;
    public Vechicle(int id,String registration)
    {
        Id = id;
        Registration = registration;
    }
    public override string ToString()
    {
        return Id.ToString() + " " + Registration;
    }

    #region getters/setters
    public int Id{
        get { return _Id; }
        set { _Id = value; }
    }

    public String Registration
    {
        get { return _Registration; }
        set { _Registration = value; }
    }

    #endregion
}

}

Was it helpful?

Solution

bogza.anton's answer is right, you need to provide a constructor without parameters, I give a sample like this:

[Serializable]
public class Vechicle
{

    private int _Id;
    private String _Registration;
    public Vechicle()
    {
        _Id = 1;
        _Registration = "default name";
    }
    public Vechicle(int id, String registration)
    {
        Id = id;
        Registration = registration;
    }
    public override string ToString()
    {
        return Id.ToString() + " " + Registration;
    }

    #region getters/setters
    public int Id
    {
        get { return _Id; }
        set { _Id = value; }
    }

    public String Registration
    {
        get { return _Registration; }
        set { _Registration = value; }
    }

    #endregion
}

private void button1_Click(object sender, EventArgs e)
    {
        List<Vechicle> vList = new List<Vechicle>()
        {
            new Vechicle(),
            new Vechicle(),
            new Vechicle{Id=2, Registration="hello"},
            new Vechicle{Id = 100, Registration="world"}
        };

        XmlSerializer SerializerObjVechicle = new XmlSerializer(vList.GetType());
        FileStream fs = new FileStream("d:\\test.xml", FileMode.OpenOrCreate);
        SerializerObjVechicle.Serialize(fs, vList);
    }

result of my test is below: picture of result

OTHER TIPS

Need to add a constructor without parameters. Or inherit class from interface ISerializable.

http://msdn.microsoft.com/en-us/library/vstudio/ms233843(v=vs.110).aspx

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top