English 中文(简体)
Easier way to serialize C# class as XML text
原标题:

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">
    <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 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());
    }
}
问题回答

Simply if you want to use UTF8 encoding then do it like this

public class StringWriterUtf8 : System.IO.StringWriter
{
    public override Encoding Encoding
    {
        get
        {
            return Encoding.UTF8;
        }
    }

}

and then use StringWriterUtf8 insread of StringWriter like this

        using (StringWriterUtf8 textWriter = new StringWriterUtf8())
        {

            serializer.Serialize(textWriter, tr, ns);

            xmlText = textWriter.ToString();
        }

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

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




相关问题
Anyone feel like passing it forward?

I m the only developer in my company, and am getting along well as an autodidact, but I know I m missing out on the education one gets from working with and having code reviewed by more senior devs. ...

NSArray s, Primitive types and Boxing Oh My!

I m pretty new to the Objective-C world and I have a long history with .net/C# so naturally I m inclined to use my C# wits. Now here s the question: I feel really inclined to create some type of ...

C# Marshal / Pinvoke CBitmap?

I cannot figure out how to marshal a C++ CBitmap to a C# Bitmap or Image class. My import looks like this: [DllImport(@"test.dll", CharSet = CharSet.Unicode)] public static extern IntPtr ...

How to Use Ghostscript DLL to convert PDF to PDF/A

How to user GhostScript DLL to convert PDF to PDF/A. I know I kind of have to call the exported function of gsdll32.dll whose name is gsapi_init_with_args, but how do i pass the right arguments? BTW, ...

Linqy no matchy

Maybe it s something I m doing wrong. I m just learning Linq because I m bored. And so far so good. I made a little program and it basically just outputs all matches (foreach) into a label control. ...

热门标签