Friday, March 14, 2008

C# : How to convert an object to xml string?

using System.Xml;
using System.Xml.Serialization;
using System.IO;

public string GetXMLFromObject(object o)
{
XmlSerializer XmlS = new XmlSerializer(o.GetType());

StringWriter sw = new StringWriter();
XmlTextWriter tw = new XmlTextWriter(sw);

XmlS.Serialize(tw, o);
return sw.ToString();
}

6 comments:

  1. What is result?

    ReplyDelete
  2. @Anonymous: You can pass an object to it and this method will return you a corresponding XML string.

    ReplyDelete
  3. I think @Anonymous was asking what the "result" variable inside the serialize method of XmlS on the second to last line was. I'd also like to know what that is.

    ReplyDelete
  4. Oh guys, I'm really sorry. It was my mistake. Its not 'result'. It should have been the object 'o' which we receive as the input. I've modified the code.

    ReplyDelete
  5. Thanks for putting answer.

    ReplyDelete
  6. How do we go back?

    ReplyDelete