开发者

Xml Serialization / Deserialization Problem

开发者 https://www.devze.com 2023-01-12 02:09 出处:网络
After writing and reading an xml string to and from a stream, it ceases to be deserializable. The new string is clipped.

After writing and reading an xml string to and from a stream, it ceases to be deserializable. The new string is clipped.

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.Posit开发者_StackOverflow中文版ion = 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.

Any suggestions as to how to fix this or what is causing the problem? My only guess is that there is some form of encoding issue, but I wouldn't know how to go about finding/fixing it.

Additionally, myObj has a generic dictionary member, which typically isn't serializable, so I have stolen code from Paul Welter in order to serialize it.


Try flushing and disposing or even better simplify your code using a StringReader:

string xmlContent = getContentFromMyDataBase();
var xs = new XmlSerializer(typeof(MyObj));
using (var reader = new StringReader(xmlContent))
{
    var theObj = (MyObj)xs.Deserialize(reader);
}

Note: The getContentFromMyDataBase method also suggests that you are storing XML in your database that you are deserializing back to an object. Don't.


You need to Flush or Close (closing implicitly flushes) the StreamWriter, or you cannot be sure it is done writing to the underlying stream. This is because it is doing some internal buffering.

Try this:

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();
0

精彩评论

暂无评论...
验证码 换一张
取 消