Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #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)
- {
- var ms = new MemoryStream();
- var xs = new XmlSerializer(objectToSerialize.GetType());
- var textWriter = new XmlTextWriter(ms, Encoding.UTF8);
- 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 xs = new XmlSerializer(typeof(T));
- var ms = new MemoryStream(UTF8Encoding.UTF8.GetBytes(xmlString));
- var textWriter = new XmlTextWriter(ms, Encoding.UTF8);
- var data = (T)xs.Deserialize(ms);
- return data;
- }
- #endregion
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement