/ Published in: C#
URL: http://msdn.microsoft.com/en-us/library/ms233843.aspx
Expand |
Embed | Plain Text
#region " XML Serialization " /// <summary> /// serialize an object to XML /// </summary> /// <typeparam name="T">the type of the input object</typeparam> /// <param name="objectToSerialize">the object to serialize</param> /// <returns></returns> public static string XmlSerialize<T>(T objectToSerialize) { xs.Serialize(textWriter, objectToSerialize); ms = (MemoryStream)textWriter.BaseStream; var xmlString = UTF8Encoding.UTF8.GetString(ms.ToArray()); // HACK : do this PI scrubbing more elegantly ... if (xmlString.StartsWith("?<?xml version=\"1.0\" encoding=\"utf-8\"?>")) xmlString = xmlString.Replace("?<?xml version=\"1.0\" encoding=\"utf-8\"?>", string.Empty); return xmlString; } /// <summary> /// deserialize an object from xml /// </summary> /// <typeparam name="T">the type definition for the return object</typeparam> /// <param name="xmlString">the serialized object xml</param> /// <returns>the deserialized object</returns> public static T XmlDeserialize<T>(string xmlString) { var data = (T)xs.Deserialize(ms); return data; } #endregion
Comments
Subscribe to comments
You need to login to post a comment.

You forgot to dispose the MemoryStream instances!