Root element is missing and XDocument and SeeOrigin.Begin

by jmorris 6. May 2009 02:45

I was writing some unit tests for a project I am currently working and kept getting the following non-useful exception:

I have seen the error before many times in the past, but I could not put my finger on what was causing it. The code is pretty simple, it just creates and instance of an object that implements IXmlSerializable passing in a stream which internally adds additional chicled object to the stream and then loads the result into a XmlReader. The the XmlReader then outputs the results to the standard console (note that a little later I add assertations to validate that the data was 'extracted' correctly):

 

Needless to say, this code failed every time on XDocument.Load with the 'Root element missing' exception.  I vaguely remember getting this error sometime in the past, but couldn't put my finger on it. I finally ran across this blog post and a light bulb went off.



After writer.Flush() is called the position of the stream is EOF. Before you can read the stream you must set the position of the stream to the begining. Note that calling writer.BaseStream.Position = 0 does _not_ work. You must call writer.BaseStream.Seek(0, SeekOrigin.Begin) to reset the streams position before creating the reader and loading the XDocument object. Also, note that the error only occurs because the XDocument object thknks the XML stream is invalid.

Tags: , , , ,

Comments (1) -

PerformanceDude.com
PerformanceDude.com
4/13/2011 7:31:01 AM #

Thanks! I had a similar problem where I was trying to serialize an object to an XML stream and read it through XDocument. Calling seek as you proposed did the trick.

Jeff Morris

Widget Tag cloud not found.

Unable to cast object of type 'ASP.widgets_tag_cloud_widget_ascx' to type 'App_Code.Controls.WidgetBase'.X

Widget Month List not found.

Unable to cast object of type 'ASP.widgets_month_list_widget_ascx' to type 'App_Code.Controls.WidgetBase'.X

Widget Page List not found.

Unable to cast object of type 'ASP.widgets_page_list_widget_ascx' to type 'App_Code.Controls.WidgetBase'.X

Widget Blogroll not found.

Unable to cast object of type 'ASP.widgets_blogroll_widget_ascx' to type 'App_Code.Controls.WidgetBase'.X

Widget Visitor info not found.

Unable to cast object of type 'ASP.widgets_visitor_info_widget_ascx' to type 'App_Code.Controls.WidgetBase'.X

Widget Visitor info not found.

Unable to cast object of type 'ASP.widgets_visitor_info_widget_ascx' to type 'App_Code.Controls.WidgetBase'.X