在一个列表多发性对象类型XmlSerialization [英] XmlSerialization of mutiple object types in the one list

查看:99
本文介绍了在一个列表多发性对象类型XmlSerialization的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有了抽象的aninamls列表的对象。即

  VAR动物=新的动物
{
新鸟{TailFeatherColour =蓝},
新型卡特彼勒{颜色=布朗}
};



使用XmlSerializer

,是有可能序列化上面下面的XML,



 <?XML版本=1.0编码=UTF-16>?; 
<动物>
<禽类GT;
< TailFeatherColour>蓝色< / TailFeatherColour>
< /鸟>
< CAT和GT;
<&色彩GT;布朗和LT; /彩色>
< /猫>
< /动物和GT;



在此刻,我只能得到如下:

 <?XML版本=1.0编码=UTF-16>?; 
<动物>
<动物的xsi:type =鸟>
< TailFeatherColour>蓝色< / TailFeatherColour>
< /动物>
<动物的xsi:type =猫>
<&色彩GT;布朗和LT; /彩色>
< /动物>
< /动物和GT; // MSDN:


解决方案

XmlElementAttribute 和的 XmlArrayItemAttribute 属性可以用来做此当列表是在另一个类的字段(不同之处在于,前者不把容器元件周围的列表元素,而后者一样)。



我不相信你可以实现你想要的只是一个列表,即当被序列化的实际对象是什么列表(尽管我可能是错在这里),但是你可以通过内部嵌套列表捏造事实一类,如:

  [XmlRoot(动物)] 
[XmlType将(动物)
公共类AnimalsWrapper
{
[XmlElement的(typeof运算(鸟)的ElementName =鸟)]
[XmlElement的(typeof运算(CAT)的ElementName =猫)]
公开名单<动物>动物;
}



这是一个笨重的黑客的一点点,但会序列化到你重新寻找。


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>

解决方案

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.

这篇关于在一个列表多发性对象类型XmlSerialization的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆