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.


Copy this code and paste it in your HTML
  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));
  6.  
  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


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.