我正在尝试序列化一个对象,并且\ 0(Null)字符被附加到生成的字符串。为什么呢?
我的代码:
XmlSerializer serializer = new XmlSerializer(typeof(Common.PlanogramSearchOptions));
MemoryStream memStream = new MemoryStream();
serializer.Serialize(memStream, searchOptions);
string xml = Encoding.UTF8.GetString(memStream.GetBuffer()); // appends \0
我的工作是用空字符串替换Null字符
xml.Replace("\0", string.Empty)
感谢。
答案 0 :(得分:11)
MemoryStream.GetBuffer()返回MemoryStream的底层缓冲区(大于存储在其中的实际数据)。你想要MemoryStream.ToArray()。
但是,我建议您使用StringWriter代替MemoryStream,这样就可以避免UTF-8转换:
XmlSerializer serializer = new XmlSerializer(typeof(PlanogramSearchOptions));
StringWriter writer = new StringWriter();
serializer.Serialize(writer, searchOptions);
string xml = writer.ToString();