Serialize plain clean XML in .NET
- by Jon Canning
public static string ToXml<T>(this T obj) where T : class
{
using (var stringWriter = new StringWriter())
{
var xmlWriterSettings = new XmlWriterSettings { OmitXmlDeclaration = true };
using (var xmlWriter = XmlWriter.Create(stringWriter, xmlWriterSettings))
{
var xmlSerializerNamespaces = new XmlSerializerNamespaces(new[] { XmlQualifiedName.Empty });
var xmlSerializer = new XmlSerializer(typeof(T));
xmlSerializer.Serialize(xmlWriter, obj, xmlSerializerNamespaces);
}
return stringWriter.ToString();
}
}