XML Serialization of C# Objects

To serialize a C# object to XML you need XmlSerializer class.

1. Create a Customer class for example

[Serializable, XmlRoot("Customer"), XmlType("Customer")]
public class Customer
{
	private String _name;
	private String _address;
	private String _tel;
	private String _fax;
	private String _vat_registration_number;
	private String _tax_office;
	private String _id;
 
	/// <summary>
	/// 
	/// </summary>
	public Customer()
	{
		_name = "";
		_address = "";
		_tel = "";
		_fax = "";
		_vat_registration_number = "";
		_tax_office = "";
		_id = "1";
	}
 
	[XmlElement("ID")]
	public String ID
	{
		get
		{
			return _id;
		}
 
		set
		{
			_id = value;
		}
	}
 
	[XmlElement("Name")]
	public String Name
	{
		get
		{
			return _name;
		}
 
		set
		{
			_name = value;
		}
	}
 
	[XmlElement("Address")]
	public String Address
	{
		get
		{
			return _address;
		}
 
		set
		{
			_address = value;
		}
	}
 
	[XmlElement("Telephone")]
	public String Telephone
	{
		get
		{
			return _tel;
		}
 
		set
		{
			_tel = value;
		}
	}
 
	[XmlElement("Fax")]
	public String Fax
	{
		get
		{
			return _fax;
		}
 
		set
		{
			_fax = value;
		}
	}
 
	[XmlElement("VatRegistrationNumber")]
	public String VatRegistrationNumber
	{
		get
		{
			return _vat_registration_number;
		}
 
		set
		{
			_vat_registration_number = value;
		}
	}
 
	[XmlElement("TaxOffice")]
	public String TaxOffice
	{
		get
		{
			return _tax_office;
		}
 
		set
		{
			_tax_office = value;
		}
	}
}

2. Serialize Object with the following code

XmlSerializer serializer = new XmlSerializer(typeof(Customer));
TextWriter tw = new StreamWriter(customer_name + ".xml");
serializer.Serialize(tw, this);
tw.Close();

3. Open xml file

<Customer xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <ID>blablabla</ID>
  <Name>blablabla</Name>
  <Address>blablabla</Address>
  <Telephone>blablabla</Telephone>
  <Fax>blablabla</Fax>
  <VatRegistrationNumber>blablabla</VatRegistrationNumber>
  <TaxOffice>blablabla</TaxOffice>
</Customer>

Enjoy!

Categories: C# Tags: , , , ,
%d bloggers like this: