using System.Collections.Generic;
using System.Xml.Serialization;
using System.Diagnostics;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Text.RegularExpressions;
using System.Globalization;
using System.ComponentModel.DataAnnotations;
using System.Collections;
using System.Runtime.InteropServices;
using System.Runtime.Serialization;
[XmlElement(typeof(ChildElementA))]
[XmlElement(typeof(ChildElementB))]
public BaseChildElement[] MyChildren { get; set; }
public abstract class BaseChildElement { }
public class ChildElementA : BaseChildElement
public string Content { get; set; }
public class ChildElementB : BaseChildElement
public string BContent { get; set; }
internal static void Test()
MyChildren = new BaseChildElement []
new ChildElementA { Content = "foo" },
new ChildElementB { BContent = "bar" },
new ChildElementA { Content = "tlon" },
new ChildElementB { BContent = "ukbar" },
Console.WriteLine("Initially serialized XML: ");
var test2 = xml.LoadFromXml<MyElement>();
var xml2 = test2.GetXml();
Console.WriteLine("Deserialized and re-serialized XML: ");
Assert.IsTrue(XNode.DeepEquals(XElement.Parse(xml), XElement.Parse(xml2)));
Console.WriteLine("Initial and re-serialized XML are equivalent.");
Assert.IsTrue(test.MyChildren.Length == test2.MyChildren.Length
&& test.MyChildren.Select(c => c.GetType()).SequenceEqual(test2.MyChildren.Select(c => c.GetType())));
Console.WriteLine("Initial and de-serialized MyChildren collections have identical lengths and child types.");
public static void Main()
public static class XmlSerializationHelper
public static T LoadFromXml<T>(this string xmlString, XmlSerializer serial = null)
serial = serial ?? new XmlSerializer(typeof(T));
T returnValue = default(T);
using (StringReader reader = new StringReader(xmlString))
object result = serial.Deserialize(reader);
public static string GetXml<T>(this T obj, XmlSerializer serializer = null, bool omitStandardNamespaces = false)
XmlSerializerNamespaces ns = null;
if (omitStandardNamespaces)
ns = new XmlSerializerNamespaces();
using (var textWriter = new StringWriter())
var settings = new XmlWriterSettings() { Indent = true };
using (var xmlWriter = XmlWriter.Create(textWriter, settings))
(serializer ?? new XmlSerializer(obj.GetType())).Serialize(xmlWriter, obj, ns);
return textWriter.ToString();
public class AssertionFailedException : System.Exception
public AssertionFailedException() : base() { }
public AssertionFailedException(string s) : base(s) { }
public static class Assert
public static void IsTrue(bool value)
throw new AssertionFailedException("failed");