XML 序列化可序列化对象的通用列表 [英] XML Serialize generic list of serializable objects
问题描述
我可以序列化一个通用的可序列化对象列表而不必指定它们的类型吗.
Can I serialize a generic list of serializable objects without having to specify their type.
类似于以下损坏代码背后的意图:
Something like the intention behind the broken code below:
List<ISerializable> serializableList = new List<ISerializable>();
XmlSerializer xmlSerializer = new XmlSerializer(serializableList.GetType());
serializableList.Add((ISerializable)PersonList);
using (StreamWriter streamWriter = System.IO.File.CreateText(fileName))
{
xmlSerializer.Serialize(streamWriter, serializableList);
}
对于那些想了解细节的人:当我尝试运行此代码时,它在 XMLSerializer[...] 行上出错:
For those who wanted to know detail: when I try to run this code, it errors on the XMLSerializer[...] line with:
无法序列化接口 System.Runtime.Serialization.ISerializable.
Cannot serialize interface System.Runtime.Serialization.ISerializable.
如果我更改为 List
,我会收到 生成 XML 文档时出错."
.InnerException 详细信息是 "{"The type System.Collections.Generic.List1[[Project1.Person, ConsoleFramework, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]] 不能在此上下文中使用."}"
If I change to List<object>
I get "There was an error generating the XML document."
. The InnerException detail is "{"The type System.Collections.Generic.List1[[Project1.Person, ConsoleFramework, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]] may not be used in this context."}"
person 对象定义如下:
The person object is defined as follows:
[XmlRoot("Person")]
public class Person
{
string _firstName = String.Empty;
string _lastName = String.Empty;
private Person()
{
}
public Person(string lastName, string firstName)
{
_lastName = lastName;
_firstName = firstName;
}
[XmlAttribute(DataType = "string", AttributeName = "LastName")]
public string LastName
{
get { return _lastName; }
set { _lastName = value; }
}
[XmlAttribute(DataType = "string", AttributeName = "FirstName")]
public string FirstName
{
get { return _firstName; }
set { _firstName = value; }
}
}
PersonList 只是一个 List
.
The PersonList is just a List<Person>
.
不过这只是为了测试,所以没觉得细节太重要.关键是我有一个或多个不同的对象,所有这些对象都是可序列化的.我想将它们全部序列化为一个文件.我认为最简单的方法是将它们放在一个通用列表中并一次性序列化该列表.但这不起作用.
This is just for testing though, so didn't feel the details were too important. The key is I have one or more different objects, all of which are serializable. I want to serialize them all to one file. I thought the easiest way to do that would be to put them in a generic list and serialize the list in one go. But this doesn't work.
我也尝试过 List
,但失败了
I tried with List<IXmlSerializable>
as well, but that fails with
System.Xml.Serialization.IXmlSerializable 无法序列化,因为它没有无参数构造函数.
抱歉缺乏细节,但我是这方面的初学者,不知道需要什么细节.如果要求更多细节的人尝试以一种让我了解需要哪些细节或概述可能方向的基本答案的方式做出回应,那将会很有帮助.
Sorry for the lack of detail, but I am a beginner at this and don't know what detail is required. It would be helpful if people asking for more detail tried to respond in a way that would leave me understanding what details are required, or a basic answer outlining possible directions.
另外感谢到目前为止我得到的两个答案 - 我本可以花更多时间阅读而不会有这些想法.令人惊讶的是,人们在这个网站上的帮助是多么大.
Also thanks to the two answers I've got so far - I could have spent a lot more time reading without getting these ideas. It's amazing how helpful people are on this site.
推荐答案
我有一个针对具有动态绑定项的通用 List<> 的解决方案.
I have an solution for a generic List<> with dynamic binded items.
class PersonalList 它是根元素
class PersonalList it's the root element
[XmlRoot("PersonenListe")]
[XmlInclude(typeof(Person))] // include type class Person
public class PersonalList
{
[XmlArray("PersonenArray")]
[XmlArrayItem("PersonObjekt")]
public List<Person> Persons = new List<Person>();
[XmlElement("Listname")]
public string Listname { get; set; }
// Konstruktoren
public PersonalList() { }
public PersonalList(string name)
{
this.Listname = name;
}
public void AddPerson(Person person)
{
Persons.Add(person);
}
}
class Person 它是一个列表元素
class Person it's an single list element
[XmlType("Person")] // define Type
[XmlInclude(typeof(SpecialPerson)), XmlInclude(typeof(SuperPerson))]
// include type class SpecialPerson and class SuperPerson
public class Person
{
[XmlAttribute("PersID", DataType = "string")]
public string ID { get; set; }
[XmlElement("Name")]
public string Name { get; set; }
[XmlElement("City")]
public string City { get; set; }
[XmlElement("Age")]
public int Age { get; set; }
// Konstruktoren
public Person() { }
public Person(string name, string city, int age, string id)
{
this.Name = name;
this.City = city;
this.Age = age;
this.ID = id;
}
}
类 SpecialPerson 继承了 Person
class SpecialPerson inherits Person
[XmlType("SpecialPerson")] // define Type
public class SpecialPerson : Person
{
[XmlElement("SpecialInterests")]
public string Interests { get; set; }
public SpecialPerson() { }
public SpecialPerson(string name, string city, int age, string id, string interests)
{
this.Name = name;
this.City = city;
this.Age = age;
this.ID = id;
this.Interests = interests;
}
}
类 SuperPerson 继承 Person
class SuperPerson inherits Person
[XmlType("SuperPerson")] // define Type
public class SuperPerson : Person
{
[XmlArray("Skills")]
[XmlArrayItem("Skill")]
public List<String> Skills { get; set; }
[XmlElement("Alias")]
public string Alias { get; set; }
public SuperPerson()
{
Skills = new List<String>();
}
public SuperPerson(string name, string city, int age, string id, string[] skills, string alias)
{
Skills = new List<String>();
this.Name = name;
this.City = city;
this.Age = age;
this.ID = id;
foreach (string item in skills)
{
this.Skills.Add(item);
}
this.Alias = alias;
}
}
和主要测试源
static void Main(string[] args)
{
PersonalList personen = new PersonalList();
personen.Listname = "Friends";
// normal person
Person normPerson = new Person();
normPerson.ID = "0";
normPerson.Name = "Max Man";
normPerson.City = "Capitol City";
normPerson.Age = 33;
// special person
SpecialPerson specPerson = new SpecialPerson();
specPerson.ID = "1";
specPerson.Name = "Albert Einstein";
specPerson.City = "Ulm";
specPerson.Age = 36;
specPerson.Interests = "Physics";
// super person
SuperPerson supPerson = new SuperPerson();
supPerson.ID = "2";
supPerson.Name = "Superman";
supPerson.Alias = "Clark Kent";
supPerson.City = "Metropolis";
supPerson.Age = int.MaxValue;
supPerson.Skills.Add("fly");
supPerson.Skills.Add("strong");
// Add Persons
personen.AddPerson(normPerson);
personen.AddPerson(specPerson);
personen.AddPerson(supPerson);
// Serialize
Type[] personTypes = { typeof(Person), typeof(SpecialPerson), typeof(SuperPerson) };
XmlSerializer serializer = new XmlSerializer(typeof(PersonalList), personTypes);
FileStream fs = new FileStream("Personenliste.xml", FileMode.Create);
serializer.Serialize(fs, personen);
fs.Close();
personen = null;
// Deserialize
fs = new FileStream("Personenliste.xml", FileMode.Open);
personen = (PersonalList)serializer.Deserialize(fs);
serializer.Serialize(Console.Out, personen);
Console.ReadLine();
}
重要的是定义并包括不同类型.
Important is the definition and includes of the diffrent types.
这篇关于XML 序列化可序列化对象的通用列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!