In the following code, I serialize an object into an XML string.
But when I try to read this XML string into an XDocument
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();
}
}
}
}
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.
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! =)