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 like the class has been set up for serialization, but I'm not sure how to get the XML representation. My class definition looks like this:
[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.1")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true, Namespace = "http://www.domain.com/test")]
[System.Xml.Serialization.XmlRootAttribute(Namespace = "http://www.domain.com/test", IsNullable = false)]
public partial class MyObject
{
...
}
Here is what I thought I could do, but it doesn't work:
MyObject o = new MyObject();
// Set o properties
string xml = o.ToString();
How do I get the XML representation of this object?
All upvoted answers above are correct. This is just simplest version:
I will start with the copy answer of Ben Gripka:
I used this code earlier. But reality showed that this solution is a bit problematic. Usually most of programmers just serialize setting on save and deserialize settings on load. This is an optimistic scenario. Once the serialization failed, because of some reason, the file is partly written, XML file is not complete and it is invalid. In consequence XML deserialization does not work and your application may crash on start. If the file is not huge, I suggest first serialize object to
MemoryStream
then write the stream to the File. This case is especially important if there is some complicated custom serialization. You can never test all cases.The deserialization in real world scenario should count with corrupted serialization file, it happens sometime. Load function provided by Ben Gripka is fine.
And it could be wrapped by some recovery scenario. It is suitable for settings files or other files which can be deleted in case of problems.
The following function can be copied to any object to add an XML save function using the System.Xml namespace.
To create the object from the saved file, add the following function and replace [ObjectType] with the object type to be created.
Here is a good tutorial on how to do this
You should basically use
System.Xml.Serialization.XmlSerializer
class to do this.I modified mine to return a string rather than use a ref variable like below.
Its usage would be like this:
Or you can add this method to your object: