Advertisement
Willcode4cash

XML (De)Serialization

Sep 22nd, 2016
106
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.38 KB | None | 0 0
  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
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement