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

前端 未结 3 2419
攒了一身酷
攒了一身酷 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 13:57

    You can resolve your problem by using a StreamReader to convert the data in the MemoryStream to a string instead:

    public static string SerializeObject<T>(object o)
    {
        using (MemoryStream ms = new MemoryStream())
        {
            XmlSerializer xs = new XmlSerializer(typeof(T));
            using (XmlWriter xtw = XmlWriter.Create(ms))
            {
                xs.Serialize(xtw, o);
                xtw.Flush();
                ms.Seek(0, SeekOrigin.Begin);
                using (StreamReader reader = new StreamReader(ms))
                {
                    return reader.ReadToEnd();
                }
            }
        }
    }
    
    0 讨论(0)
  • 2021-02-20 14:04

    It's because the data contains the unicode or utf8 BOM marks at the start of the stream.

    You need to skip past any Byte Order Marks in the stream - you can identify these from the System.Text.Encoding.GetPreamble() method.

    0 讨论(0)
  • 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<T>(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! =)

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