Serialize data of objects compiled in a class library

4

Greetings, I have a problem with a serialization exercise. The theme is the following: I have a ClassLibrary with the classes Fruit (abstract), Apple and Banana that are derived from Fruit and another class Cajon that contains a list of "fruits", the program works correctly for me except for an error when serializing:

public bool SerializarXML()
    {
        bool success = false;
        try
        {
            Type[] extras = new Type[2];
            extras[0] = typeof(Manzana);
            extras[1] = typeof(Platano);
            using (XmlTextWriter xtw = new XmlTextWriter("C:\Cajon.xml", Encoding.UTF8))
            {
                XmlSerializer xs = new XmlSerializer(typeof(Cajon), extras);
                xs.Serialize(xtw, this);
                success = true;
            }
        }
        catch (Exception e)
        {
            Console.WriteLine(e.Message); ;
        }
        return success;
    }

All classes are public, and contains bookmarks:

 [Serializable]

in the fruit class also contains:

[XmlInclude(typeof(Manzana))]
[XmlInclude(typeof(Platano))]

But it throws me an error that says: Error al reflejar el tipo SP2015.Manzana , where SP2015 is the name of the namespace. I also clarify that the Main is in ANOTHER project, of the Consola type, where I try to call the SerializarXML () method. Any ideas?

    
asked by stdinh2491 21.06.2016 в 19:55
source

1 answer

3

But you're not serializing data, you're sending the Type object to the serialization

public bool SerializarXML(List<Fruta> datos)
{
    bool success = false;
    try
    {
        using (XmlTextWriter xtw = new XmlTextWriter("C:\Cajon.xml", Encoding.UTF8))
        {
            XmlSerializer xs = new XmlSerializer(typeof(Fruta));
            xs.Serialize(xtw, datos);
            success = true;
        }
    }
    catch (Exception e)
    {
        Console.WriteLine(e.Message);
    }
    return success;
}

As you will notice, you send a List < > of Fruit to serialize, but they are data using it in this way

List<Fruta> list = new List<Fruta>();
list.Add(new Manzana());
list.Add(new Platano());

SerializarXML(list);
    
answered by 21.06.2016 в 20:18