user462166 user462166 - 1 month ago 28
C# Question

Serialize an object to XML

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?

Answer

You have to use XmlSerializer for XML serialization. Below is a sample snippet.

 XmlSerializer xsSubmit = new XmlSerializer(typeof(MyObject));
 var subReq = new MyObject();
 StringWriter sww = new StringWriter();
 using(XmlWriter writer = XmlWriter.Create(sww))
 {
     xsSubmit.Serialize(writer, subReq);
     var xml = sww.ToString(); // Your XML
 }