How do I have to change this XML string so that XDocument.Parse reads it in?

前端 未结 3 2341
攒了一身酷
攒了一身酷 2021-02-20 13:25

In the following code, I serialize an object into an XML string.

But when I try to read this XML string into an XDocument

3条回答
  •  执念已碎
    2021-02-20 14:07

    All above is correct, and here is a code that you should use instead of yours to skip BOM:

     public static string SerializeObject(object o)
            {
                MemoryStream ms = new MemoryStream();
                XmlSerializer xs = new XmlSerializer(typeof(T));
                //here is my code
                UTF8Encoding encoding = new UTF8Encoding(false);
                XmlTextWriter xtw = new XmlTextWriter(ms, encoding);
                //XmlTextWriter xtw = new XmlTextWriter(ms, Encoding.UTF8);
                xs.Serialize(xtw, o);
                ms = (MemoryStream)xtw.BaseStream;
                return StringHelpers.UTF8ByteArrayToString(ms.ToArray());
           }
    

    By specifying false in the constructor you say "BOM is not provided". Enjoy! =)

提交回复
热议问题