XML serialization in CSharp

Serializing an object in C# is relatively easy, as shown by the code below.

Output of Conversion
  John Doe 1970-01-01T00:00:00 0001-01-01T00:00:00 

Optional Modifications
In order to hide the namespace definitions in the &lt;Person&gt; line, the main function can be modified to the following:

public static string ObjToXml(object obj) {   XmlSerializerNamespaces ns = new XmlSerializerNamespaces; ns.Add("", ""); XmlSerializer xsz = new XmlSerializer(obj.GetType); StringBuilder sb = new StringBuilder; StringWriter sw = new StringWriter(sb); xsz.Serialize(sw, obj, ns); return sb.ToString; }

Controlling Serialization of Objects
By default, all public properties and fields of an object are serialized as elements of the parent node. To control how an object is serialized into XML, such as serializing as an attribute or not being serialized at all, the use of tags are employed in the code.

Example
public class Person {   [XmlAttribute(AttributeName = "FirstName")] public string GivenName;

[XmlAttribute(AttributeName = "LastName")] public string Surname; // NOTE: Cannot serialize complex data types into an attribute. It is a run-time error.

// [XmlElement] is assumed here public string Nickname;

[XmlElement] public DateTime DateBorn;

[XmlIgnore] // Does not serialize. public DateTime DateDied; }