在向流中读取xml字符串并从中读取xml字符串后,它将不再可反序列化。新字符串被剪裁。
string XmlContent = getContentFromMyDataBase();
XmlSerializer xs = new XmlSerializer(typeof(MyObj));
MemoryStream ms = new MemoryStream();
StreamWriter sw = new StreamWriter(ms);
char[] ca = XmlContent.ToCharArray(); // still working up to this point.
ms.Position = 0;
sw.Write(ca);
StreamReader sr = new StreamReader(ms);
ms.Position = 0;
string XmlContentAgain = sr.ReadToEnd();
Console.WriteLine(XmlContentAgain); // (outputstring is too short.)
MyObj theObj = (MyObj)xs.Deserialize(ms); // Can't deserialize.
有关如何解决此问题或导致问题的原因的任何建议?我唯一的猜测是存在某种形式的编码问题,但我不知道如何寻找/修复它。
此外,myObj有一个通用字典成员,通常不可序列化,所以我从Paul Welter窃取了代码以便序列化它。
答案 0 :(得分:2)
尝试使用StringReader
来刷新和处理甚至更好地简化代码string xmlContent = getContentFromMyDataBase();
var xs = new XmlSerializer(typeof(MyObj));
using (var reader = new StringReader(xmlContent))
{
var theObj = (MyObj)xs.Deserialize(reader);
}
注意:getContentFromMyDataBase
方法还建议您在数据库中存储要反序列化回对象的XML。不。
答案 1 :(得分:0)
您需要刷新或关闭(关闭隐式刷新)StreamWriter,否则您无法确定是否已完成写入基础流。这是因为它正在做一些内部缓冲。
试试这个:
using(StreamWriter sw = new StreamWriter(ms))
{
char[] ca = XmlContent.ToCharArray(); // still working up to this point.
ms.Position = 0;
sw.Write(ca);
}
StreamReader sr = new StreamReader(ms);
ms.Position = 0;
string XmlContentAgain = sr.ReadToEnd();