XmlSerialization of mutiple object types in the one list

孤人 提交于 2020-01-13 19:57:09

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!