Root element is missing and XDocument and SeeOrigin.Begin

by jmorris 5/5/2009 11:45:00 AM

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.

Currently rated 5.0 by 2 people

  • Currently 5/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Tags: , , , ,

C# | XML

Related posts

Comments

Powered by BlogEngine.NET 1.3.1.0
Theme by Mads Kristensen

Jeff Morris

Name of author Occasional rants about software development and software engineering in general.

E-mail me Send mail

Calendar

<<  March 2010  >>
MoTuWeThFrSaSu
22232425262728
1234567
891011121314
15161718192021
22232425262728
2930311234

View posts in large calendar

Pages

    Recent comments

    Authors

    Disclaimer

    The opinions expressed herein are my own personal opinions and do not represent my employer's view in anyway.

    © Copyright 2010

    Sign in