Back to all blogs3 min read
How to serialize an object to XML string?
You can use below method to serialize an object to XML string.
Ankush Jain
Lead Software Engineer (VP) | Software Architect
Published Aug 5, 2017Updated Nov 24, 2026
You can use below method to serialize an object to XML string.
Namespaces required:
using System.Xml.Serialization;using System.IO;Method definition:
public string GetXMLString<T>(T objectToSerialize){ XmlSerializer xmlSerializer = new XmlSerializer(objectToSerialize.GetType());
using (StringWriter stringWriter = new System.IO.StringWriter()) { xmlSerializer.Serialize(stringWriter, objectToSerialize); return stringWriter.ToString(); }}