// Collection of code snippets by Arne Vajhøj // (likely posted to comp.os.vms/INFO-VAX, INFO-TPU, MACRO32, eksperten.dk, newz.dk, LinkedIn or other place sometime between 1990 and now) using System; using System.Collections; using System.Collections.Generic; using System.IO; using System.Linq; using System.Xml.Serialization; namespace E { public abstract class Person { private List infoList; private string name; public Person() { } public Person(string name, List myList) { this.name = name; infoList = myList; } public string Name { get { return name; } set { name = value; } } public List InfoList { get { return infoList; } set { infoList = value; } } } public class Student : Person { private string collage; public Student() { } public Student(string name, string collage, List myList) : base(name, myList) { this.collage = collage; } public string Collage { get { return collage; } set { collage = value; } } } public class Info { private string name; private string[] grade; public Info() { } public string[] Grade { get { return grade; } set { grade = value; } } public Info(string name, string[] grade) { this.name = name; this.grade = grade; } } public static class XMLSerialization { private static void GetAdditionalTypes(object obj, HashSet addtyp) { addtyp.Add(obj.GetType()); if(obj is IEnumerable) { foreach(object elm in (IEnumerable)obj) { GetAdditionalTypes(elm, addtyp);; } } } private static Type[] GetAdditionalTypes(object obj) { HashSet addtyp = new HashSet(); GetAdditionalTypes(obj, addtyp); return addtyp.ToArray(); } public static void XMLSerialize(string filePath, T obj) { using (FileStream fs = new FileStream(filePath, FileMode.Create)) { XmlSerializer XmlSer = new XmlSerializer(typeof(T), GetAdditionalTypes(obj)); XmlSer.Serialize(fs, obj); } } } public class Program { public static void Main(string[] args) { List personList = new List(); string[] itemArray = {"item1","item2","item3"}; Info infoFull = new Info("Test1", itemArray); List infoList = new List(); infoList.Add(infoFull); Person p1 = new Student("olle", "sundsta",infoList); personList.Add(p1); Person[] personArray = personList.ToArray(); XMLSerialization.XMLSerialize(@"C:\z.xml", personArray); } } }