Willcode4cash icon

XML (De)Serialization

Willcode4cash | PRO | 09/23/16 04:15:30 AM UTC | 0 ⭐ | 247 👁️ | Never ⏰ | []
C# |

1.38 KB

|

None

|

0 👍

/

0 👎

#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

Comments