This simple example shows how to serialise a class as XML. It is an easy way of getting the a full textual copy of the class structure, no matter how complicated the class is. In the past I have seen this used for logging values of a class instance.
First of all we need an class. I have made these up, with a few different types.
public class Person
{
public string FirstName { get; set; }
public string LastName { get; set; }
public DateTime DOB { get; set; }
public Address Address { get; set; }
public int NoOfDependents { get; set; }
public double Height { get; set; }
}
public class Address
{
public string Address1 { get; set; }
public string Address2 { get; set; }
public string Town { get; set; }
public string City { get; set; }
public string PostCode { get; set; }
}
And an instance of the class with some data. For this example I am actually creating a list of Person objects.
var listOfPeople = new List<Person>();
listOfPeople.Add(new Person
{
DOB = DateTime.Today,
FirstName = "Bernadette",
LastName = "Williams-Harrison",
NoOfDependents = 2,
Height = 4.6,
Address = new Address
{
Address1 = "2345 Dead End Street",
Address2 = string.Empty,
City = "Pembely",
PostCode = "BB67 9PP",
Town = "Little Stichins",
}
});
listOfPeople.Add(new Person
{
DOB = DateTime.Today,
FirstName = "Andrew",
LastName = "Carton",
NoOfDependents = 1,
Height = 6.0,
Address = new Address
{
Address1 = "11 Park View",
Address2 = "Chester House",
City = string.Empty,
PostCode = "CM1 4BY",
Town = "Mordon",
}
});
And the final part is the code to perform the sreialisation.
var xmlSerializer = new XmlSerializer(listOfPeople.GetType()); var textWriter = new StringWriter(); xmlSerializer.Serialize(textWriter, listOfPeople); var result = textWriter.ToString();
The result variable will be of string type, containing XML. This is what it looks like
<?xml version="1.0" encoding="utf-16"?>
<ArrayOfPerson xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<Person>
<FirstName>Bernadette</FirstName>
<LastName>Williams-Harrison</LastName>
<DOB>2014-05-14T00:00:00+01:00</DOB>
<Address>
<Address1>2345 Dead End Street</Address1>
<Address2 />
<Town>Little Stichins</Town>
<City>Pembely</City>
<PostCode>BB67 9PP</PostCode>
</Address>
<NoOfDependents>2</NoOfDependents>
<Height>4.6</Height>
</Person>
<Person>
<FirstName>Andrew</FirstName>
<LastName>Carton</LastName>
<DOB>2014-05-14T00:00:00+01:00</DOB>
<Address>
<Address1>11 Park View</Address1>
<Address2>Chester House</Address2>
<Town>Mordon</Town>
<City />
<PostCode>CM1 4BY</PostCode>
</Address>
<NoOfDependents>1</NoOfDependents>
<Height>6</Height>
</Person>
</ArrayOfPerson>
One thing to note is the resulting text may contain formatting characters, such as \r, \n, \” or others. Do with them what you will.

One thought on “Serialise a class to XML in C#”