using System.Collections.Generic;
using System.Xml.Serialization;
using System.ComponentModel;
public Account() { this.AccountNodes = new List<AccountNode>(); }
public List<AccountNode> AccountNodes { get; set; }
[Browsable(false), EditorBrowsable(EditorBrowsableState.Never)]
public XElement[] AccountNodesXml
if (AccountNodes == null)
return AccountNodes.Select(a => new XElement((XName)a.Name, a.Value)).ToArray();
AccountNodes = value.Select(e => new AccountNode { Name = e.Name.LocalName, Value = (string)e }).ToList();
public String Name { get; set; }
public String Value { get; set; }
<AccountNumber>12345</AccountNumber>
public static void Test()
Console.WriteLine("Original XML: ");
var account = xml.LoadFromXml<Account>();
var xml2 = account.GetXml(true);
Console.WriteLine("Deserialized and reserialized XML for {0}: ", account);
if (!XNode.DeepEquals(XElement.Parse(xml), XElement.Parse(xml2)))
Console.WriteLine("Old and new XML are NOT equivalent.");
throw new InvalidOperationException("!XNode.DeepEquals(XElement.Parse(xml), XElement.Parse(xml2))");
Console.WriteLine("Old and new XML are 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();