Convert Object to XML Document genric methode

Some time we need to create the XML document to get or post from service, so every time instead of creating the document we will create the generic method to generate the XML document in object and list of objects.
For that here is the code for single object
  1. public XmlDocument ConvertObjectToXML<T>(T objectToConvert) where T : class
  2. {
  3. XmlDocument doc = new XmlDocument();
  4. Type sourceType = objectToConvert.GetType();
  5. XmlElement root = doc.CreateElement(sourceType.Name + "s");
  6. XmlElement rootChild = doc.CreateElement(sourceType.Name);
  7. PropertyInfo[] sourceProperties = sourceType.GetProperties();
  8. foreach (PropertyInfo pi in sourceProperties)
  9. {
  10. if (pi.GetValue(objectToConvert, null) != null)
  11. {
  12. XmlElement child = doc.CreateElement(pi.Name);
  13. child.InnerText = Convert.ToString(pi.GetValue(objectToConvert, null));
  14. rootChild.AppendChild(child);
  15. }
  16. }
  17. root.AppendChild(rootChild);
  18. doc.AppendChild(root);
  19. return doc;
  20. }
  21. for List of objects
  22. public List<XmlElement> ConvertObjectToXML<T> (List<T> lstObjectToConvert, XmlDocument xDoc) where T : class
  23. {
  24. List<XmlElement> root = new List<XmlElement>();
  25. if (lstObjectToConvert.Count > 0)
  26. {
  27. for (int i = 0; i < lstObjectToConvert.Count; i++)
  28. {
  29. T objectToConvert = lstObjectToConvert[i];
  30. XmlElement rootChild = xDoc.CreateElement(lstObjectToConvert[0].GetType().Name);
  31. Type sourceType = objectToConvert.GetType();
  32. PropertyInfo[] sourceProperties = sourceType.GetProperties();
  33. foreach (PropertyInfo pi in sourceProperties)
  34. {
  35. if (pi.GetValue(objectToConvert, null) != null)
  36. {
  37. XmlElement child = xDoc.CreateElement(pi.Name);
  38. if (pi.ToString().Contains("System.Collections.Generic.List"))
  39. {
  40. if (pi.GetValue(objectToConvert, null).GetType() == typeof(List<Address>))
  41. {
  42. List<Address> lstAddress = (List<Address>)pi.GetValue(objectToConvert, null);
  43. List<XmlElement> rootChild1 = ConvertObjectToXML<Address>(lstAddress, xDoc);
  44. if (rootChild1 != null)
  45. {
  46. foreach (XmlElement item in rootChild1)
  47. {
  48. child.AppendChild(item);
  49. }
  50. }
  51. }
  52. }
  53. else
  54. {
  55. child.InnerText = Convert.ToString(pi.GetValue(objectToConvert, null));
  56. }
  57. rootChild.AppendChild(child);
  58. }
  59. }
  60. root.Add(rootChild);
  61. }
  62. }
  63. return root;
  64. }