I followed the link that StriplingWarrior gave and found this great answer. fooobar.com/questions/467357 / ... from webturner
I changed its implementation and made the Class ListOfToDo class, which implemented both List and IXmlSerializable. It worked! Here is my modified code.
using System; using System.Collections.Generic; using System.IO; using System.Xml; using System.Xml.Schema; using System.Xml.Serialization; namespace ConsoleApplication1 { public interface IDoTest { void DoTest(); void Setup(); } public class TestDBConnection : IDoTest { public string DBName; public void DoTest() { Console.WriteLine("DoHardComplicated Test"); } public void Setup() { Console.WriteLine("SetUpDBTest"); } } public class PingTest : IDoTest { public string ServerName; public void DoTest() { Console.WriteLine("MaybeDoAPing"); } public void Setup() { Console.WriteLine("SetupAPingTest"); } } public class ListOfToDo : List<IDoTest>, **IXmlSerializable** { #region IXmlSerializable public XmlSchema GetSchema(){ return null; } public void ReadXml(XmlReader reader) { reader.ReadStartElement("ListOfToDo"); while (reader.IsStartElement("IDoTest")) { Type type = Type.GetType(reader.GetAttribute("AssemblyQualifiedName")); XmlSerializer serial = new XmlSerializer(type); reader.ReadStartElement("IDoTest"); this.Add((IDoTest)serial.Deserialize(reader)); reader.ReadEndElement();
The output will be as follows:
<?xml version="1.0" encoding="utf-8"?> <ListOfToDo> <IDoTest AssemblyQualifiedName="ConsoleApplication1.TestDBConnection, ConsoleApplication1, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null"> <TestDBConnection xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"> <DBName>SQLDB</DBName> </TestDBConnection> </IDoTest> <IDoTest AssemblyQualifiedName="ConsoleApplication1.PingTest, ConsoleApplication1, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null"> <PingTest xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"> <ServerName>AccTestServ_5</ServerName> </PingTest> </IDoTest> </ListOfToDo>
source share