简体   繁体   English

具有不同子类的XML序列化

[英]XML Serialization with Different Subclasses

I have a super class and two subclasses and I want to serialize the objects of the subclasses as a list and deserialize it 我有一个超类和两个子类,我想将这些子类的对象序列化为列表并反序列化

I tried to use a super class list which had objects from both subclasses but ended up in an exception. 我试图使用一个超类列表,该列表具有两个子类中的对象,但最终出现异常。

Is there any way to do it? 有什么办法吗?

Type1 t = new Type1() { text="123" ,opt1=true,opt2=true};
Type2 t1 = new Type2() { text="1234",isAnswer=false};
Question q1 = new Question() { text="12321"};
Question q2 = new Question() { text = "12321" };
List<Question> q = new List<Question>() { t1 };
FileStream fs = new FileStream("aa.xml", FileMode.OpenOrCreate, FileAccess.Write);
XmlSerializer xs = new XmlSerializer(typeof(List<Question>));
//Exception is generated here InvalidOperationException
//there was error genearating the XML document
xs.Serialize(fs, q);

fs.Close();

Try passing the types to be known to the serializer, such as, 尝试将序列号已知的类型传递给,例如,

serializer = new XmlSerializer(typeof(T), extraTypes); where extraTypes is an array of types that you have to be serialized. 其中extraTypes是必须序列化的类型数组。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM