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 flags flags { get; set; }
const string SummonableName = "summonable";
const string AttackableName = "attackable";
public int summonable { get; set; }
public int attackable { get; set; }
[Browsable(false), EditorBrowsable(EditorBrowsableState.Never), DebuggerBrowsable(DebuggerBrowsableState.Never)]
new Flag { Name = SummonableName, Value = XmlConvert.ToString(summonable) },
new Flag { Name = AttackableName, Value = XmlConvert.ToString(attackable) },
foreach (var attr in value)
if (attr.Name == SummonableName)
summonable = XmlConvert.ToInt32(attr.Value);
else if (attr.Name == AttackableName)
attackable = XmlConvert.ToInt32(attr.Value);
public string Name { get; set; }
public string Value { get; set; }
public XmlAttribute[] XmlAttributes
var attr = new XmlDocument().CreateAttribute(Name.ToString());
if (value == null || value.Length == 0)
else if (value.Length == 1)
throw new ArgumentException("Too many attributes");
internal static void Test()
var monster = new monster
var xml = monster.GetXml(true);
Console.WriteLine("Serialized XML: ");
var monster2 = xml.LoadFromXML<monster>();
var xml2 = monster2.GetXml(true);
Console.WriteLine("Deserialized and re-serialized XML: ");
if (!(monster.flags.summonable == monster2.flags.summonable && monster.flags.attackable == monster2.flags.attackable))
throw new InvalidOperationException("!(monster.flags.summonable == monster2.flags.summonable && monster.flags.attackable == monster2.flags.attackable)");
Console.WriteLine("Round trip serialization successful.");
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();