Xml serializing and deserializing with memory stream [duplicate]

╄→гoц情女王★ 提交于 2020-01-24 04:44:40

问题


I'm getting an error with the following code where it can't find a root element when it tries to deserialize the code:

An exception of type 'System.InvalidOperationException' occurred in System.Xml.dll but was not handled in user code
Additional information: There is an error in XML document (0, 0).
Inner exception: {"Root element is missing."}

It seems straightforward enough code, but googling and searching SO on the issue hasn't yielded any clear answers--only similar issues that are nonetheless that the answer don't help... or I'm misunderstanding something.

    [TestMethod]
    public void TestSerialize()
    {
        XmlSerializer serializer = new XmlSerializer(testObject.GetType());
        MemoryStream memStream = new MemoryStream();
        serializer.Serialize(memStream, testObject);

        XmlSerializer xmlSerializer = new XmlSerializer(testObject.GetType());
        TestObject testObj = ((TestObject)xmlSerializer.Deserialize(memStream));
        assert(testObject == testObj);
    }

public class TestObject
{
    public int IntProp { get; set; }
    public string StringProp { get; set; }
}

The alleged duplicate question at Root element is missing uses XMLDocument objects and has a different correct answer.


回答1:


After serialization, the MemoryStream's position is > 0. You need to reset it before reading from it.

memStream.Position = 0;

Or...

memStream.Seek(0, SeekOrigin.Begin);



回答2:


You might want to reset the postition of your MemoryStream as after having serialized your XML to it the position will be at the end.

memStream.Position = 0;
XmlSerializer = new XmlSerializer(testObject.GetType());
TestObject testObj = ((TestObject)xmlSerialzer.Deserialize(memStream));


来源:https://stackoverflow.com/questions/30698349/xml-serializing-and-deserializing-with-memory-stream

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!