Easier way to serialize C# class as XML text

前端 未结 4 1340
醉梦人生
醉梦人生 2020-12-16 03:07

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:<

相关标签:
4条回答
  • 2020-12-16 03:34

    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());
        }
    }
    
    0 讨论(0)
  • 2020-12-16 03:41

    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();
            }
    
    0 讨论(0)
  • 2020-12-16 03:47

    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();
    }
    
    0 讨论(0)
  • 2020-12-16 03:48

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

    0 讨论(0)
提交回复
热议问题