Hinweis
Für den Zugriff auf diese Seite ist eine Autorisierung erforderlich. Sie können versuchen, sich anzumelden oder das Verzeichnis zu wechseln.
Für den Zugriff auf diese Seite ist eine Autorisierung erforderlich. Sie können versuchen, das Verzeichnis zu wechseln.
There are many reasons for custom serialization of an object into a human readable string (e.g. XML). If you find yourself recreating the serialization/deserialization code every few weeks, perhaps, it’s time to save off the functions below into a class in a shared assembly J.
public static string ToXml<T>(T source)
{
string result = null;
using (System.IO.StringWriter sw = new System.IO.StringWriter())
{
using (System.Xml.XmlWriter writer = System.Xml.XmlTextWriter.Create(sw, null))
{
System.Xml.Serialization.XmlSerializer serializer = new System.Xml.Serialization.XmlSerializer(typeof(T));
serializer.Serialize(writer, source);
}
result = sw.ToString();
}
return result;
}
public static T FromXml<T>(string xml)
{
T result = default(T);
if (string.IsNullOrEmpty(xml) == false)
{
using (System.IO.StringReader sr = new System.IO.StringReader(xml))
{
System.Xml.Serialization.XmlSerializer serializer = new System.Xml.Serialization.XmlSerializer(typeof(T));
result = (T) serializer.Deserialize(sr);
}
}
return result;
}
Comments
Anonymous
March 27, 2007
How fast do these methods run?Anonymous
March 27, 2007
I don't have any numbers at this time... But since it's a very good question, I put it on my list of things to do -- stay tuned, the answer will be posted in one of the upcoming blog posts in the next few days.Anonymous
April 03, 2007
In my post SYSK 315 ( http://blogs.msdn.com/irenak/archive/2007/03/27/sysk-315-generic-functions-for-object-xml-serialization-deserialization.aspx