Geeks With Blogs
Gavin Stevens's Blog the ramblings of another developer....

I was trying a very simple prototype of manually serializing objects and storing them in a memory stream.  Obviously this sample is not the final implementation, it's just a test.  So tell me why I get this stupid error....  here is the code:

Imports System.Xml.Serialization
Imports System.IO
Imports System.Xml
Imports System.Text

<Serializable()> _
Public Class TestObject
Public Firstname As String
Public lastname As String
Public DOB As Date
Public age As Integer
End
Class

Try
Dim oTO As New TestObject
oTO.Firstname = "John"
oTO.lastname = "Doe"
oTO.DOB = "02/13/1972"
oTO.age = 32

'Serialize Object to Memory Stream
Dim oSerializer As New XmlSerializer(GetType(TestObject))
Dim oMemStream As New MemoryStream
oSerializer.Serialize(oMemStream, oTO)

'Deserialize Object
oTO = CType(oSerializer.Deserialize(oMemStream), TestObject)
Console.WriteLine(oTO.Firstname & " " & oTO.lastname)
Console.WriteLine(oTO.DOB & " " & oTO.age)

Catch ex As Exception
Console.WriteLine(ex.ToString)
End Try
End Sub

Thats it, pretty simple, but I get this error:

System.InvalidOperationException: There is an error in XML document (0, 0). ---> System.Xml.XmlException: The root element is missing.
at System.Xml.XmlTextReader.Read()
at System.Xml.XmlReader.MoveToContent()
at Microsoft.Xml.Serialization.GeneratedAssembly.XmlSerializationReader1.Read4_TestObject()
--- End of inner exception stack trace ---
at System.Xml.Serialization.XmlSerializer.Deserialize(XmlReader xmlReader, String encodingStyle)
at System.Xml.Serialization.XmlSerializer.Deserialize(Stream stream)

Posted on Monday, August 9, 2004 3:39 AM | Back to top


Comments on this post: Object Serialization.. someone help me out here.. this is lame

# re: Object Serialization.. someone help me out here.. this is lame
Requesting Gravatar...
After you serialize, the position of oMemStream object is at the end. You need to reset it to 0.

Between the Serialize and Deserialize section, enter the following line:

oMemStream.Position = 0

That should do the trick.

James
Left by James Steele on Aug 10, 2004 2:31 AM

# re: Object Serialization.. someone help me out here.. this is lame
Requesting Gravatar...
Hi, I had the same problem and I've been stuck on it for a while but Jame's suggestion did the trick.

Thanks!
Left by Big Joe on Nov 21, 2006 7:56 PM

# re: Object Serialization.. someone help me out here.. this is lame
Requesting Gravatar...
THANK YOU!!!! I've been looking at a fix for this for the last 3 hours! Setting the position to 0 did the trick!
Left by BZ on Jun 18, 2009 1:52 PM

Your comment:
 (will show your gravatar)


Copyright © Gavin Stevens | Powered by: GeeksWithBlogs.net | Join free