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

6/4/2010 7:54:24 PM #

เล่นเกมส์ฟรี

I really appreciate this wonderful post that you have provided for us. I assure this would be beneficial for most of the people.

เล่นเกมส์ฟรี United States | Reply

8/10/2010 11:12:21 AM #

Nihat

I cannot thank you enough for this post! I had similar problem and have been pulling my hair over this.

Nihat United States | Reply

4/13/2011 7:31:01 AM #

PerformanceDude.com

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.

PerformanceDude.com United States | Reply

11/22/2011 6:05:45 PM #

Technology Blog

Just want to say your article is as astonishing. The clearness in your post is simply spectacular and i could assume you\'re an expert on this subject. Fine with your permission allow me to grab your RSS feed to keep up to date with forthcoming post. Thanks a million and please continue the gratifying work.  Thanks !

Technology Blog | Reply

Add comment


(Will show your Gravatar icon)

  Country flag

biuquote
  • Comment
  • Preview
Loading



Who Am I?

My name is Jeff Morris a software engineer/developer in Southern California, USA. My platform du jour is dotnet, but I dabble on the darkside occasionally.

Tag cloud

Page List