简体   繁体   中英

Deserializing XML File using XmlSerializer.Deserialize from MemoryStream not working

I'm having trouble deserializing my XML file from a MemoryStream. I have a generated MyXmlFile class and a MemoryStream containing an XML file which I want to deserialize into an object of type MyXmlFile.

public static class XmlSerializeObject
{
    public static T FromStream<T>(Stream s)
    {
        var serializer = new XmlSerializer(typeof(T));
        return (T) serializer.Deserialize(s);
    }
}

I have a MemoryStream ms which contains an xml file. If I try to deserialize that stream into an object of type MyXmlFile I get an exception "There is an error in XML document (0,0)"

MyXmlFile test = XmlSerializeObject.FromStream<MyXmlFile>(ms);

However I verified that my MemoryStream is correct. If I first write my stream into a file on my disc and than read that file again it works fine.

        FileStream outStream = File.OpenWrite("D:\\p.xml");
        outStream.Write(((MemoryStream)ms).ToArray(), 0, ((MemoryStream)ms).ToArray().Length);
        outStream.Flush();
        outStream.Close();
        MyXmlFile test= XmlSerializeObject.FromStream<MyXmlFile>(File.OpenRead("D:\\p.xml"));

I was not able to find a solution myself that is why I decided to post my question. Maybe someone had the same problem before and is able to help me out.

Thanks in advance. If anything is unclear please ask.

If you instantiated your memory stream prior to your call to deserialize (say, to load the XML into the memory stream in the first place) it may be that it's at the wrong index. Try

ms.Seek(0, SeekOrigin.Begin)

To go back to the beginning of the stream.

You must set position of MemoryStream to the 0.

((MemoryStream)ms).Position = 0;
MyXmlFile test = XmlSerializeObject.FromStream<MyXmlFile>(ms);

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