XML Serializer

Other Serialization technologies include Binary and JSON Serialization.

System.Xml.Serialization

The stream should be wrapped in a using statement for production ready code.

1
2
3
4
5
var stream = new MemoryStream();
var xmlSerializer = new XmlSerializer(typeof(someObject));
xmlSerializer.Serialize(stream, self);
stream.Position = 0; // same as `stream.Seek(0, SeekOrigin.Begin);`
stream.Close();

Caveat

The object being serialized needs to have a parameterless constructor.

1
2
3
4
5
6
7
8
9
public class Person
{
public string FirstName;
public Address Address;

public Person()
{
}
...

References