Try following methods:
public static class XmlSerializer<T> where T : class
{
public static string Serialize(T obj)
{
XmlSerializer xsSubmit = new XmlSerializer(typeof(T));
using (var sww = new StringWriter())
{
using (XmlTextWriter writer = new XmlTextWriter(sww) { Formatting = Formatting.None })
{
xsSubmit.Serialize(writer, obj);
return sww.ToString();
}
}
}
public static string SerializeOmitXmlDeclaration<T>(T value)
{
var emptyNamespaces = new XmlSerializerNamespaces(new[] { XmlQualifiedName.Empty });
var serializer = new XmlSerializer(value.GetType());
var settings = new XmlWriterSettings();
settings.Indent = true;
settings.OmitXmlDeclaration = true;
using (var stream = new StringWriter())
using (var writer = XmlWriter.Create(stream, settings))
{
serializer.Serialize(writer, value, emptyNamespaces);
return stream.ToString();
}
}
}
Use it as
var xml = XmlSerializer<List<CustomerDemo>>.SerializeOmitXmlDeclaration(customerList);
Posted On:
06-Mar-2023 23:43