Posted By

hobeau43 on 07/28/11


Tagged


Versions (?)

Who likes this?

2 people have marked this snippet as a favorite

Priestd09
danfinrud55


C# Xml Serializer Functions


 / Published in: C#
 

URL: http://msdn.microsoft.com/en-us/library/ms233843.aspx

  1. #region " XML Serialization "
  2.  
  3. /// <summary>
  4. /// serialize an object to XML
  5. /// </summary>
  6. /// <typeparam name="T">the type of the input object</typeparam>
  7. /// <param name="objectToSerialize">the object to serialize</param>
  8. /// <returns></returns>
  9. public static string XmlSerialize<T>(T objectToSerialize)
  10. {
  11. var ms = new MemoryStream();
  12. var xs = new XmlSerializer(objectToSerialize.GetType());
  13. var textWriter = new XmlTextWriter(ms, Encoding.UTF8);
  14. xs.Serialize(textWriter, objectToSerialize);
  15. ms = (MemoryStream)textWriter.BaseStream;
  16. var xmlString = UTF8Encoding.UTF8.GetString(ms.ToArray());
  17.  
  18. // HACK : do this PI scrubbing more elegantly ...
  19. if (xmlString.StartsWith("?<?xml version=\"1.0\" encoding=\"utf-8\"?>"))
  20. xmlString = xmlString.Replace("?<?xml version=\"1.0\" encoding=\"utf-8\"?>", string.Empty);
  21.  
  22. return xmlString;
  23. }
  24.  
  25. /// <summary>
  26. /// deserialize an object from xml
  27. /// </summary>
  28. /// <typeparam name="T">the type definition for the return object</typeparam>
  29. /// <param name="xmlString">the serialized object xml</param>
  30. /// <returns>the deserialized object</returns>
  31. public static T XmlDeserialize<T>(string xmlString)
  32. {
  33. var xs = new XmlSerializer(typeof(T));
  34. var ms = new MemoryStream(UTF8Encoding.UTF8.GetBytes(xmlString));
  35. var textWriter = new XmlTextWriter(ms, Encoding.UTF8);
  36. var data = (T)xs.Deserialize(ms);
  37. return data;
  38. }
  39.  
  40. #endregion

Report this snippet  

Comments

RSS Icon Subscribe to comments
Posted By: fixpq on February 26, 2012

You forgot to dispose the MemoryStream instances!

You need to login to post a comment.