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
I have a simple way to serialize an object to XML using C#, it works great and it's highly reusable. I know this is an older thread, but I wanted to post this because someone may find this helpful to them.
Here is how I call the method:
var objectToSerialize = new MyObject();
var xmlString = objectToSerialize.ToXmlString();
Here is the class that does the work:
Note: Since these are extension methods they need to be in a static class.
using System.IO;
using System.Xml.Serialization;
public static class XmlTools
{
public static string ToXmlString(this T input)
{
using (var writer = new StringWriter())
{
input.ToXml(writer);
return writer.ToString();
}
}
private static void ToXml(this T objectToSerialize, StringWriter writer)
{
new XmlSerializer(typeof(T)).Serialize(writer, objectToSerialize);
}
}