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 List<KeyValuePair<string, object>> Items { get; set; }
[Browsable(false), EditorBrowsable(EditorBrowsableState.Never), DebuggerBrowsable(DebuggerBrowsableState.Never)]
public XElement[] XmlItems
return Items.Select(p => new XElement(p.Key, (p.Value ?? string.Empty).ToString())).ToArray();
Items = Items ?? new List<KeyValuePair<string, object>>(value.Length);
Items.Add(new KeyValuePair<string, object>(e.Name.LocalName, e.Value));
public static void Test()
var root = new RootObject
System.Drawing.Color.AliceBlue,
.Select((o, i) => new KeyValuePair<string, object>("Key" + i.ToString(), o))
private static void Test(RootObject root)
var xml = root.GetXml(true);
var root2 = xml.LoadFromXML<RootObject>();
var xml2 = root2.GetXml(true);
if (!XNode.DeepEquals(XElement.Parse(xml), XElement.Parse(xml2)))
throw new InvalidOperationException("!XNode.DeepEquals(XElement.Parse(xml), XElement.Parse(xml2))");
Console.WriteLine("Serialized and re-serialized XML look equivalent.");
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();