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
- public XmlDocument ConvertObjectToXML<T>(T objectToConvert) where T : class
- {
- XmlDocument doc = new XmlDocument();
-
- Type sourceType = objectToConvert.GetType();
-
- XmlElement root = doc.CreateElement(sourceType.Name + "s");
- XmlElement rootChild = doc.CreateElement(sourceType.Name);
-
- PropertyInfo[] sourceProperties = sourceType.GetProperties();
- foreach (PropertyInfo pi in sourceProperties)
- {
- if (pi.GetValue(objectToConvert, null) != null)
- {
- XmlElement child = doc.CreateElement(pi.Name);
- child.InnerText = Convert.ToString(pi.GetValue(objectToConvert, null));
- rootChild.AppendChild(child);
- }
- }
-
- root.AppendChild(rootChild);
- doc.AppendChild(root);
-
- return doc;
-
- }
-
- for List of objects
- public List<XmlElement> ConvertObjectToXML<T> (List<T> lstObjectToConvert, XmlDocument xDoc) where T : class
- {
- List<XmlElement> root = new List<XmlElement>();
- if (lstObjectToConvert.Count > 0)
- {
-
- for (int i = 0; i < lstObjectToConvert.Count; i++)
- {
- T objectToConvert = lstObjectToConvert[i];
-
- XmlElement rootChild = xDoc.CreateElement(lstObjectToConvert[0].GetType().Name);
-
- Type sourceType = objectToConvert.GetType();
- PropertyInfo[] sourceProperties = sourceType.GetProperties();
- foreach (PropertyInfo pi in sourceProperties)
- {
- if (pi.GetValue(objectToConvert, null) != null)
- {
- XmlElement child = xDoc.CreateElement(pi.Name);
- if (pi.ToString().Contains("System.Collections.Generic.List"))
- {
-
- if (pi.GetValue(objectToConvert, null).GetType() == typeof(List<Address>))
- {
- List<Address> lstAddress = (List<Address>)pi.GetValue(objectToConvert, null);
- List<XmlElement> rootChild1 = ConvertObjectToXML<Address>(lstAddress, xDoc);
- if (rootChild1 != null)
- {
- foreach (XmlElement item in rootChild1)
- {
- child.AppendChild(item);
- }
- }
- }
-
-
- }
- else
- {
- child.InnerText = Convert.ToString(pi.GetValue(objectToConvert, null));
-
- }
- rootChild.AppendChild(child);
-
- }
- }
- root.Add(rootChild);
- }
-
- }
- return root;
-
-
- }