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

前端 未结 3 2340
攒了一身酷
攒了一身酷 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(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();
                }
            }
        }
    }
    

提交回复
热议问题