Easier way to serialize C# class as XML text

前端 未结 4 1359
醉梦人生
醉梦人生 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: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();
            }
    

提交回复
热议问题