views:

496

answers:

3

While trying to answer another question, I was serializing a C# object to an XML string. It was surprisingly hard; this was the shortest code snippet I could come up with:

var yourList = new List<int>() { 1, 2, 3 };
var ms = new MemoryStream();
var xtw = new XmlTextWriter(ms, Encoding.UTF8);
var xs = new XmlSerializer(yourList.GetType());
xs.Serialize(xtw, yourList);
var encoding = new UTF8Encoding();
string xmlEncodedList = encoding.GetString(ms.GetBuffer());

The result is okay:

<?xml version="1.0" encoding="utf-8"?>
<ArrayOfInt
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:xsd="http://www.w3.org/2001/XMLSchema"&gt;
    <int>1</int>
    <int>2</int>
    <int>3</int>
</ArrayOfInt>

But the snippet is more complicated than I think it should be. I can't believe you have to know about encoding and MemoryStream for this simple task.

Is there a shorter way to serialize an object to an XML string?

A: 

Write an extension method or a wrapper class/function to encapsulate the snippet.

Uwe Keim
That doesn't particularly make it simpler - just relocates the complexity (though it does imply a level of reuse).
Murph
+7  A: 

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());
}
Darin Dimitrov
Even shorter if you don't do `GetStringBuilder()`
Konstantin Spirin
Thanks, SQL Server accepted only the UTF-8 version. I guess this is as simple as it gets in C#...
Andomar
@Andomar: I hadn't seen this question before... you can avoid some of this code using my Utf8StringWriter class. See http://stackoverflow.com/questions/3862063
Jon Skeet
A: 

You don't need the MemoryStream, just use a StringWriter :

var yourList = new List<int>() { 1, 2, 3 };
using (StringWriter sw = new StringWriter())
{
    var xs = new XmlSerializer(yourList.GetType());
    xs.Serialize(sw, yourList);
    string xmlEncodedList = sw.ToString();
}
Thomas Levesque
That will be UTF-16, not UTF-8
Garry Shutler