// 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.Generic; using System.Xml; using System.Xml.Serialization; namespace E { public class typex { } public class type1 : typex { public String tekst { get; set; } } public class type2 : typex { public String tekst { get; set; } } public class type3 : typex { public String tekst { get; set; } } public class xmltest { [XmlElement(Type = typeof(type1)), XmlElement(Type = typeof(type2)), XmlElement(Type = typeof(type3))] public List typex { get; set; } } public class Program { public static void Dump(xmltest o) { foreach(typex tx in o.typex) { switch(tx.GetType().Name) { case "type1": type1 t1 = (type1)tx; Console.WriteLine("Type1 : {0}", t1.tekst); break; case "type2": type2 t2 = (type2)tx; Console.WriteLine("Type2 : {0}", t2.tekst); break; case "type3": type3 t3 = (type3)tx; Console.WriteLine("Type3 : {0}", t3.tekst); break; } } } public static void Main(string[] args) { XmlSerializer ser = new XmlSerializer(typeof(xmltest), new Type[] { typeof(type1), typeof(type2), typeof(type3) }); XmlReader rdr = new XmlTextReader("/Work/test.xml"); while(rdr.Read()) { switch(rdr.NodeType) { case XmlNodeType.Element: XmlReader subrdr = rdr.ReadSubtree(); xmltest o = (xmltest)ser.Deserialize(subrdr); Dump(o); subrdr.Close(); break; default: // ignore break; } } rdr.Close(); } } }