简体   繁体   中英

Xml Serialization / Deserialization Problem

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.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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM