user462166 user462166 - 2 months ago 45
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.Xml.Serialization.XmlTypeAttribute(AnonymousType = true, Namespace = "")]
[System.Xml.Serialization.XmlRootAttribute(Namespace = "", 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?


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