I have a C# class that I have inherited. I have successfully \"built\" the object. But I need to serialize the object to XML. Is there an easy way to do it?
It looks
Based on above solutions, here comes a extension class which you can use to serialize and deserialize any object. Any other XML attributions are up to you.
Just use it like this:
string s = new MyObject().Serialize(); // to serialize into a string
MyObject b = s.Deserialize();// deserialize from a string
internal static class Extensions
{
public static T Deserialize(this string value)
{
var xmlSerializer = new XmlSerializer(typeof(T));
return (T)xmlSerializer.Deserialize(new StringReader(value));
}
public static string Serialize(this T value)
{
if (value == null)
return string.Empty;
var xmlSerializer = new XmlSerializer(typeof(T));
using (var stringWriter = new StringWriter())
{
using (var xmlWriter = XmlWriter.Create(stringWriter, new XmlWriterSettings { Indent = true }))
{
xmlSerializer.Serialize(xmlWriter, value);
return stringWriter.ToString();
}
}
}
}