Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Xml serialization appending the \0 (backslash 0 or Null) character?

I am trying to serialize an object and the \0 (Null) character is being appended to the generated string. Why?

My code:

 XmlSerializer serializer = new XmlSerializer(typeof(Common.PlanogramSearchOptions));
 MemoryStream memStream = new MemoryStream();
 serializer.Serialize(memStream, searchOptions);

 string xml = Encoding.UTF8.GetString(memStream.GetBuffer()); // appends \0

My work around is replacing the Null character with an empty string

xml.Replace("\0", string.Empty)

Thanks.

like image 264
alex.davis.dev Avatar asked Sep 23 '10 14:09

alex.davis.dev


1 Answers

MemoryStream.GetBuffer() returns the underlying buffer of the MemoryStream (which is larger than the actual data stored in it). You want MemoryStream.ToArray().

However, I recommend you use a StringWriter instead of MemoryStream, so you can avoid the UTF-8 conversion:

XmlSerializer serializer = new XmlSerializer(typeof(PlanogramSearchOptions));
StringWriter writer = new StringWriter();
serializer.Serialize(writer, searchOptions);
string xml = writer.ToString();

See also: Serialize an object to string

like image 56
dtb Avatar answered Oct 19 '22 22:10

dtb