Wednesday, February 15, 2012

[Csharp] Serialize object with XmlSerializer


XML become familiar with application developer. Working with it, I always use XmlSerializer, I can serialize xml string to an object, then I can access to element to change value.
Here is two sample classes, it will serialize string to object and forward:

   1:          public static string ToXmlString<T>(T objectToSerialize)
   2:          {
   3:              var stream = new MemoryStream();
   4:   
   5:              TextWriter writer = new StreamWriter(stream, new UTF8Encoding());
   6:   
   7:              var xmlSerializer = new XmlSerializer(typeof(T));
   8:              xmlSerializer.Serialize(writer, objectToSerialize);
   9:   
  10:              return Encoding.UTF8.GetString(stream.ToArray(), 0, Convert.ToInt32(stream.Length));
  11:          }
  12:   
  13:          public static T FromXmlString<T>(String source)
  14:          {
  15:              var xmlSerializer = new XmlSerializer(typeof(T));
  16:              var sr = new StringReader(source);
  17:              return (T)xmlSerializer.Deserialize(sr);
  18:          }
Put them on a class and try to use it :)

No comments:

Post a Comment