using System.Xml.Serialization;
public class SerializeMe : IXmlSerializable
public int A { get; set; }
public int? B { get; set; }
public int? C { get; set; }
public MyClass MyClass { get; set;}
public void WriteXml(XmlWriter writer)
Program.WriteXml<SerializeMe>(writer, this);
public void ReadXml(XmlReader reader) {}
public XmlSchema GetSchema() { return null; }
[AttributeUsage(AttributeTargets.Class)]
public class Nested : Attribute
public class MyClass : IXmlSerializable
public int Z { get; set;}
public void WriteXml(XmlWriter writer)
Program.WriteXml<MyClass>(writer, this);
public void ReadXml(XmlReader reader) {}
public XmlSchema GetSchema() { return null; }
public static void Main()
var s = XmlSerialize<SerializeMe>(new SerializeMe
MyClass = new MyClass { Z = 2},
public static string XmlSerialize<T>(T entity) where T : class
XmlWriterSettings settings = new XmlWriterSettings();
settings.OmitXmlDeclaration = true;
XmlSerializer xsSubmit = new XmlSerializer(typeof(T));
StringWriter sw = new StringWriter();
using (XmlWriter writer = XmlWriter.Create(sw, settings))
var xmlns = new XmlSerializerNamespaces();
xmlns.Add(string.Empty, string.Empty);
xsSubmit.Serialize(writer, entity, xmlns);
public static void WriteXml<T>(XmlWriter writer, T obj)
PropertyInfo[] props = obj.GetType().GetProperties();
foreach (var prop in props)
var val = prop.GetValue(obj);
if (prop.PropertyType.IsValueType ||
prop.PropertyType.IsGenericType &&
prop.PropertyType.GetGenericTypeDefinition() == typeof(Nullable<>))
writer.WriteElementString(prop.Name, val.ToString());
if (prop.PropertyType.GetCustomAttribute(typeof(Nested)) != null)
writer.WriteStartElement("UndesiredTag");
((dynamic)val).WriteXml(writer);
writer.WriteEndElement();