问题
I have an object that has a list of abstract 'aninamls'. i.e.
var animals = new Animals
{
new Bird{ TailFeatherColour = "Blue" },
new Cat{ Colour = "Brown" }
};
using the xmlserializer, is it possible to serialize the above to the following xml,
<?xml version="1.0" encoding="utf-16"?>
<Animals>
<Bird>
<TailFeatherColour>Blue</TailFeatherColour>
</Bird>
<Cat>
<Colour>Brown</Colour>
</Cat>
</Animals>
at the moment, I can only get the following:
<?xml version="1.0" encoding="utf-16"?>
<Animals>
<Animal xsi:type="Bird">
<TailFeatherColour>Blue</TailFeatherColour>
</Animal>
<Animal xsi:type="Cat">
<Colour>Brown</Colour>
</Animal>
</Animals>
回答1:
The XmlElementAttribute and XmlArrayItemAttribute attributes can be used to do this when the list is a field in another class (the difference being that the former does not put a container element around the list elements, whereas the latter does).
I don't believe you can achieve what you want with just a list, i.e. when the actual object being serialized is a list (though I could be wrong here) however you can fake it by nesting a list inside a class, e.g.
[XmlRoot("Animals")]
[XmlType("Animals")]
public class AnimalsWrapper
{
[XmlElement(typeof(Bird), ElementName = "Bird")]
[XmlElement(typeof(Cat), ElementName = "Cat")]
public List<Animal> Animals;
}
It's a little bit of a clunky hack, but will serialize to what you're looking for.
来源:https://stackoverflow.com/questions/456231/xmlserialization-of-mutiple-object-types-in-the-one-list