using System.Collections.Generic;
using System.Xml.Serialization;
using System.Diagnostics;
public string NV { get; set; }
[XmlAttribute("nil", Namespace = "http://www.w3.org/2001/XMLSchema-instance")]
public string Nil { get { return SomeEnum == null ? "true" : null; } set { } }
public bool ShouldSerializeNil() { return SomeEnum == null; }
public SomeEnum? SomeEnum { get; set; }
public string SomeEnumText
return SomeEnum.Value.ToString();
if (string.IsNullOrEmpty(value))
SomeEnum = (SomeEnum)Enum.Parse(typeof(SomeEnum), value, false);
SomeEnum = (SomeEnum)Enum.Parse(typeof(SomeEnum), value, true);
[XmlElement("testTag.01")]
public testTag01 TestTag { get; set; }
public static void Test()
Test(new TestClass { TestTag = new testTag01 { NV = "123123" } });
Test(new TestClass { TestTag = new testTag01 { NV = "123123", SomeEnum = SomeEnum.SomeValue } });
private static void Test(TestClass test)
var test2 = xml.LoadFromXML<TestClass>();
Console.WriteLine(test2.GetXml());
Debug.WriteLine(test2.GetXml());
if (test2.TestTag.NV != test.TestTag.NV)
throw new InvalidOperationException("test2.TestTag.NV != test.TestTag.NV");
public static class XmlSerializationHelper
public static T LoadFromXML<T>(this string xmlString, XmlSerializer serializer = null)
T returnValue = default(T);
using (StringReader reader = new StringReader(xmlString))
object result = (serializer ?? new XmlSerializer(typeof(T))).Deserialize(reader);
public static string GetXml<T>(this T obj, XmlSerializerNamespaces ns = null, XmlWriterSettings settings = null, XmlSerializer serializer = null)
using (var textWriter = new StringWriter())
settings = settings ?? new XmlWriterSettings() { Indent = true, IndentChars = " " };
using (var xmlWriter = XmlWriter.Create(textWriter, settings))
(serializer ?? new XmlSerializer(typeof(T))).Serialize(xmlWriter, obj, ns);
return textWriter.ToString();
public static void Main()