Easier way to serialize C# class as XML text
A little shorter :-)
var yourList = new List<int>() { 1, 2, 3 };
using (var writer = new StringWriter())
{
new XmlSerializer(yourList.GetType()).Serialize(writer, yourList);
var xmlEncodedList = writer.GetStringBuilder().ToString();
}
Although there's a flaw with this previous approach that's worth pointing out. It will generate an utf-16
header as we use StringWriter so it is not exactly equivalent to your code. To get utf-8
header we should use a MemoryStream and an XmlWriter which is an additional line of code:
var yourList = new List<int>() { 1, 2, 3 };
using (var stream = new MemoryStream())
{
using (var writer = XmlWriter.Create(stream))
{
new XmlSerializer(yourList.GetType()).Serialize(writer, yourList);
var xmlEncodedList = Encoding.UTF8.GetString(stream.ToArray());
}
}