Serialización personalizada de XmlSerializer

I have two class one of them is inherited from the other.

For example Animal this is a base class and Dog this is an inherited class.

I populated a List collection and I would like to serialize it as a List Collection.

¿Es posible?

string serializedResult = XmlSerializeHelper<List<Animal>>.Serialize(result.ToList());

Where result is a List<Dog> collection.

And XmlSerializeHelper implementation is the following:

public class XmlSerializeHelper<T> where T : class
{
    public static string Serialize(object o)
    {
        XmlSerializer xmlSerializer = new XmlSerializer(typeof(T));
        StringWriter stringWriter = new StringWriter();
        xmlSerializer.Serialize(stringWriter, o);
        return stringWriter.ToString();
    }
    public static T Deserialize(string xml)
    {
        XmlSerializer xmlSerializer = new XmlSerializer(typeof(T));
        StringReader stringReader = new StringReader(xml);
        return (T)xmlSerializer.Deserialize(stringReader);
    }
}

preguntado el 08 de noviembre de 11 a las 17:11

1 Respuestas

If you have a list ( I usually use array-lists for this ), add the xml attributes to it for all derived classes

    [XmlArray("Animal"),
     XmlArrayItem("Dog", typeof(Dog)),
     XmlArrayItem("Cat", typeof(Cat))]
    public ArrayList Animals = new ArrayList();

This tells the serializer which types it can expect...

...edit... To make it more readable, consider this:

[Serializable]
public class ListOfAnimals
{
    public ListOfAnimals(){}

    [XmlArray("Animal"),
     XmlArrayItem("Dog", typeof(Dog)),
     XmlArrayItem("Cat", typeof(Cat))]
    public ArrayList Animals = new ArrayList();
}

[Serializable]
public class Animal
    {
        public Animal(){}

        public Animal(string name)
        {
            Name = name;
        }
        public string Name{ get;set;}
}

[Serializable]
public class Dog : Animal
{
    public Dog(){}

    public bool Vaccinated{ get;set; }
}

[Serializable]
public class Cat : Animal
{
    public Cat(){}

    public bool Neutered{ get;set; }
}

then call the serialization like this:

ListOfAnimals result = new ListOfAnimals();

Dog puppy1 = new Dog();
Dog puppy2 = new Dog();
Cat kitty1 = new Cat();
Cat kitty2 = new Cat();

puppy1.Name = "Lassie";
puppy2.Name = "Yeller";
kitty1.Name = "Miauu";
kitty2.Name = "Scratchy";

result.Animals.Add(puppy1);
result.Animals.Add(puppy2);
result.Animals.Add(kitty1);
result.Animals.Add(kitty2);

string serializedResult = XmlSerializeHelper<ListOfAnimals>.Serialize(result);

respondido 08 nov., 11:21

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.