Is it possible to serialize a general list of serializable objects without specifying their type.
Something like the intent 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); }
Edit:
For those who wanted to know the details: when I try to run this code, these are errors in the XMLSerializer [...] line:
Cannot serialize the System.Runtime.Serialization.ISerializable interface.
If I go 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."}"
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 is just a List<Person> .
This is just for testing, so I didnโt feel that 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 into one file. I thought the easiest way to do this is to put them in a general list and serialize the list at a time. But that does not work.
I also tried with List<IXmlSerializable> but with an error
System.Xml.Serialization.IXmlSerializable cannot be serialized because it does not have a parameterless constructor.
Sorry for the lack of details, but I'm new to this and don't know which part is required. It would be helpful if people asking in more detail would try to answer in such a way that I could understand what details are required, or a basic answer outlining possible directions.
Also, thanks to the two answers that I still have, I could spend a lot more time reading without getting these ideas. It's amazing how useful people are on this site.