Tuesday 22 March 2011

Dot.Net: XML Serialization Sample

Question:
Do you have a standard XML serialization sample for dot.net?
How to serialize object to XML in dot.net?
What is the easiest way to transform objects to XML in dot.net?



Answer:
The easiest way is definitely using the XmlSerializer.

BUT this does not work very well when your objects get more complex! (Lists, Hashes, Class hierarchies etc.)

Up to a certain degree of complexity you can control the way in which the XmlSerializer serializes or deserializes an instance of the class by using XML Attributes .


Here is an xml example

  
    
    
  

 
Here is a sample serialization in c#
using System.Xml.Serialization;
using System.Text;
using System.IO;
...

   XmlSerializer xSer = new XmlSerializer(typeof(Friend));
   StringBuilder sb = new StringBuilder();
   StringWriter sw = new StringWriter(sb);
   xSer.Serialize(sw, aFriend);
   string s = sb.ToString();

No comments: