Posted By

rengber on 08/25/09


xml c serialization Reflection Linq

Versions (?)

Who likes this?

2 people have marked this snippet as a favorite


Dump an Arbitrary Object to XML (Bypassing Default Serialization)

 / Published in: C#

Useful in cases where the object author has specified their own serialization that doesn't work for you.

  1. public static string ObjectToString(object o)
  2. {
  3. XDocument doc = new XDocument();
  4. string objectType = o.GetType().ToString();
  5. doc.AddFirst(new XElement(objectType));
  7. foreach (PropertyInfo pi in o.GetType().GetProperties())
  8. {
  9. doc.Root.Add(new XElement(pi.Name, Convert.ToString(pi.GetValue(o, null))));
  10. }
  11. return doc.ToString();
  12. }

Report this snippet  

You need to login to post a comment.