using System.Collections.Generic;
using System.Xml.Serialization;
using System.Diagnostics;
using System.ComponentModel;
using System.Collections;
[XmlElement(IsNullable = true)]
public string string1 { get; set; }
[XmlElement(IsNullable = true)]
public string string2 { get; set; }
public bool boolean1 { get; set; }
public float float1 { get; set; }
public float float2 { get; set; }
public float float3 { get; set; }
[XmlElement("Type1", typeof(Type1), IsNullable = true)]
[XmlElement("Type2", typeof(Type2), IsNullable = true)]
[Browsable(false), EditorBrowsable(EditorBrowsableState.Never), DebuggerBrowsable(DebuggerBrowsableState.Never)]
public object [] TypeArray
var collection = Type as IEnumerable;
return collection.Cast<object>().ToArray();
var type1 = value.OfType<Type1>().ToList();
var type2 = value.Where(t => t == null || t is Type2).Cast<Type2>().ToList();
if (type2.Count == 1 && type1.Count == 0)
else if (type1.Count == value.Length)
throw new InvalidOperationException("invalid value");
public object Type { get; set; }
static string GetType1Xml()
<boolean1>true</boolean1>
<boolean1>true</boolean1>
<boolean1>true</boolean1>
public static void Test()
var xml1 = GetType1Xml();
var root = xml1.LoadFromXML<RootObject>();
var xml1Back = root.GetXml(true);
ConsoleAndDebug.WriteLine("Re-serialized Type1 collection: ");
ConsoleAndDebug.WriteLine(xml1Back);
if (!XNode.DeepEquals(XElement.Parse(xml1), XElement.Parse(xml1Back)))
throw new InvalidOperationException("!XNode.DeepEquals(XElement.Parse(xml), XElement.Parse(xml1Back))");
root.Type = new Type2 { float1 = 1.0f, float2 = 2.0f, float3 = 3.0f };
var xml2 = root.GetXml(true);
var root2 = xml2.LoadFromXML<RootObject>();
var xml2back = root2.GetXml(true);
ConsoleAndDebug.WriteLine("Re-serialized Type2 singleton: ");
ConsoleAndDebug.WriteLine(xml2back);
if (!XNode.DeepEquals(XElement.Parse(xml2), XElement.Parse(xml2back)))
throw new InvalidOperationException("!XNode.DeepEquals(XElement.Parse(xml2), XElement.Parse(xml2back))");
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, IndentChars = " " };
using (var xmlWriter = XmlWriter.Create(textWriter, settings))
new XmlSerializer(obj.GetType()).Serialize(xmlWriter, obj, ns);
return textWriter.ToString();
public static class ConsoleAndDebug
public static void WriteLine(object s)
public static void Main()