附加\ 0(反斜杠0或Null)字符的Xml序列化?

时间:2010-09-23 14:58:51

标签: c# xml-serialization

我正在尝试序列化一个对象,并且\ 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)

感谢。

1 个答案:

答案 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();

另请参阅:Serialize an object to string