How To Convert XML To String In C#

To achieve this, we can use the XmlWriter class provided by the following namespaces: "System.Xml" and "System.Xml.Serialization". Here is a custom code snippet, where the first parameter is the generic type and the second parameter is the null-able XmlWriterSettings.
  1. public static string SerializeObject<T>(T typeObj, XmlWriterSettings settings = null)  
  2.         {  
  3.             if (typeObj == null)  
  4.             {  
  5.                 return string.Empty;  
  6.             }  
  7.             try  
  8.             {  
  9.                 using (var stringWriter = new StringWriter())  
  10.                 {  
  11.                     using (var xmlWriter = XmlWriter.Create(stringWriter, settings))  
  12.                     {  
  13.                         var serializer = new XmlSerializer(typeof(T));  
  14.                         serializer.Serialize(xmlWriter, typeObj);  
  15.                         return stringWriter.ToString();  
  16.                     }  
  17.                 }  
  18.             }  
  19.             catch  
  20.             {  
  21.                 return string.Empty;  
  22.             }  
  23.         } 
Next Recommended Reading Remove Last Character from String in C#