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
The following function can be copied to any object to add an XML save function using the System.Xml namespace.
///
/// Saves to an xml file
///
/// File path of the new xml file
public void Save(string FileName)
{
using (var writer = new System.IO.StreamWriter(FileName))
{
var serializer = new XmlSerializer(this.GetType());
serializer.Serialize(writer, this);
writer.Flush();
}
}
To create the object from the saved file, add the following function and replace [ObjectType] with the object type to be created.
///
/// Load an object from an xml file
///
/// Xml file name
/// The object created from the xml file
public static [ObjectType] Load(string FileName)
{
using (var stream = System.IO.File.OpenRead(FileName))
{
var serializer = new XmlSerializer(typeof([ObjectType]));
return serializer.Deserialize(stream) as [ObjectType];
}
}