Engineering scalable systems, cloud-native applications, and AI-powered solutions.

How to serialize an object to XML string?

You can use below method to serialize an object to XML string.

Ankush Jain

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:

c#
using System.Xml.Serialization;
using System.IO;

Method definition:

c#
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();
}
}

Have feedback or thoughts?

Discuss this article or share it on Twitter / GitHub.