Search This Blog

Thursday, December 10, 2009

De/Se-rializing C# objects to XML

I have come across many projects over the years which need some sort of serializing and deserializing of C# objects to XML.  I usually remember the general syntax but more than often end up searching for the exact syntax.  There are tonnes of articles on this by the way and this blog is merely to give me a consistent way of doing this rather than anything else.

Say you have a couple of C# classes such that one class contains a collection of the other class and you want to serialize this into XML.

image

The way I usually do it is simply by adding some attributes to my C# classes which represent the structure of the resulting XML and run an XML serializer against it.  So my C# classes would potentially look like:

[XmlRoot(ElementName = "Customer", IsNullable = false)]
public class Customer
{
[XmlElement(ElementName = "Name")]
public string Name { get; set; }

[XmlElement(ElementName = "IsExpired")]
public bool IsExpired { get; set; }

[XmlElement(ElementName = "DOB")]
public DateTime DOB { get; set; }

[XmlArray("Orders")]
[XmlArrayItem("Order", Type = typeof(Order))]
public List<order> Orders { get; set; }
}

public class Order
{
[XmlAttribute(AttributeName = "OrderID")]
public int OrderID { get; set; }
}

With the above class we get an XML output as shown in the figure below:

image

And the code which actually does the serialization:

class Program
{
static void Main(string[] args)
{
Customer c = new Customer()
{
Name = "Ruskin Dantra",
DOB = DateTime.Today,
IsExpired = false,
Orders = new List<order>()
{
new Order() { OrderID = 1},
new Order() { OrderID = 2},
new Order() { OrderID = 3}
}
};

System.Xml.Serialization.XmlSerializer s = new System.Xml.Serialization.XmlSerializer(typeof(Customer));

XmlWriterSettings settings = new XmlWriterSettings();
settings.Indent = true;

XmlWriter writer = XmlWriter.Create(@"Customer.xml", settings);
s.Serialize(writer, c);
writer.Close();
}
}

If you want to deserialize the above created XML back into the object all you have to do is:

System.Xml.Serialization.XmlSerializer s = new System.Xml.Serialization.XmlSerializer(typeof(Customer));
XmlReader reader = XmlReader.Create(@"Customer.xml");
Customer deserializedCustomer = s.Deserialize(reader) as Customer;
reader.Close();

Its as easy as that :)

No comments:

Post a Comment