Created
June 4, 2012 13:27
-
-
Save Dynyx/2868367 to your computer and use it in GitHub Desktop.
XML serialization functions
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment