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;
public abstract class RootBase
public Header header { get; set; }
public abstract ContentBase BasicContent { get; }
public string elementA { get; set; }
public string elementB { get; set; }
[XmlRoot(ElementName = "root")]
public class Root<TContent> : RootBase
where TContent : ContentBase
public TContent content { get; set; }
public override ContentBase BasicContent { get { return content; } }
public abstract class ContentBase
public string elementC { get; set; }
public class ContentA : ContentBase
public VariousTypeA variousTypeA { get; set; }
public class ContentB : ContentBase
public VariousTypeB variousTypeB { get; set; }
public class VariousTypeA
public string itemA { get; set; }
public string itemB { get; set; }
public string itemC { get; set; }
public class VariousTypeB
public string itemZ { get; set; }
public string itemY { get; set; }
public string itemX { get; set; }
static string GetTypeAXml()
<elementA>Example</elementA>
<elementB>Test</elementB>
static string GetTypeBXml()
<elementA>Example</elementA>
<elementB>Test</elementB>
internal static void Test()
var xmlStringA = GetTypeAXml();
var rootA = (Root<ContentA>)new XmlSerializer(typeof(Root<ContentA>)).Deserialize(new StringReader(xmlStringA));
var newXmlA = rootA.GetXml(true);
Console.WriteLine("Deserialized and re-serialized {0}", rootA.GetType());
Console.WriteLine(newXmlA);
var xmlStringB = GetTypeBXml();
var rootB = (Root<ContentB>)new XmlSerializer(typeof(Root<ContentB>)).Deserialize(new StringReader(xmlStringB));
var newXmlB = rootB.GetXml(true);
Console.WriteLine("Deserialized and re-serialized {0}", rootB.GetType());
Console.WriteLine(newXmlB);
public static void Main()
public static class XmlSerializationHelper
public static T LoadFromXML<T>(this string xmlString)
using (StringReader reader = new StringReader(xmlString))
return (T)new XmlSerializer(typeof(T)).Deserialize(reader);
public static string GetXml<T>(this T obj, 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))
new XmlSerializer(obj.GetType()).Serialize(xmlWriter, obj, ns);
return textWriter.ToString();