using System.Collections.Generic;
using System.Xml.Serialization;
using System.Diagnostics;
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)
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);
return textWriter.ToString();
public static class ConsoleAndDebug
public static void WriteLine(object s)
[System.SerializableAttribute()]
private bool myFieldSerializes;
public Foo(string myField, bool myFieldSerializes)
this.myFieldSerializes = myFieldSerializes;
[XmlElement(IsNullable = true)]
get { return this.myField; }
set { this.myField = value; }
[System.Xml.Serialization.XmlIgnoreAttribute()]
public bool MyFieldSpecified { get { return myFieldSerializes; } set { myFieldSerializes = value; } }
public static void Test()
var test1 = new Foo { MyField = "aa", MyFieldSpecified = true };
var test2 = new Foo { MyField = "aa", MyFieldSpecified = false };
var test3 = new Foo { MyFieldSpecified = true };
var test4 = new Foo { MyFieldSpecified = false };
var tests = new [] { test1, test2, test3, test4 };
foreach (var test in tests)
ConsoleAndDebug.WriteLine(xml);
var testBack = xml.LoadFromXML<Foo>();
if (test.MyFieldSpecified != testBack.MyFieldSpecified)
throw new InvalidOperationException("test.MyFieldSpecified != testBack.MyFieldSpecified");
if (test.MyFieldSpecified && testBack.MyField != test.MyField)
throw new InvalidOperationException("test.MyFieldSpecified && testBack.MyField != test.MyField");
if (!test.MyFieldSpecified && testBack.MyField != null)
throw new InvalidOperationException("!test.MyFieldSpecified && testBack.MyField != null");
ConsoleAndDebug.WriteLine("done");
public static void Main()