Root element is missing.

The following code doesn't work; the exception message reads "Root element is missing.":

MemoryStream transformed = new MemoryStream(); XmlDocument doc = new XmlDocument(); XmlReader input = null; XslCompiledTransform xslt = new XslCompiledTransform(); input = XmlReader.Create("Example.xml"); xslt.Load("Example.xslt"); xslt.Transform(input, new XsltArgumentList(), transformed); try { doc.Load(transformed); } catch (Exception ex) { Console.WriteLine("XmlDocument.Load failed: {0}", ex.Message); } Console.ReadLine();

It isn't a problem with the input file or the transform script.  The problem is that the XslCompiledTransform.Transform function leaves the stream position set to the end of the stream.  There's no root element because the XmlDocument.Load function thinks the stream has a 0 byte length.  The fix is to simply set the position to 0:

MemoryStream transformed = new MemoryStream(); XmlDocument doc = new XmlDocument(); XmlReader input = null; XslCompiledTransform xslt = new XslCompiledTransform(); input = XmlReader.Create("Example.xml"); xslt.Load("Example.xslt"); xslt.Transform(input, new XsltArgumentList(), transformed); // THE FIX transformed.Position = 0; try { doc.Load(transformed); } catch (Exception ex) { Console.WriteLine("XmlDocument.Load failed: {0}", ex.Message); } Console.ReadLine();

Print | posted @ Thursday, November 15, 2007 7:23 AM

Comments on this entry:

Gravatar # re: Root element is missing.
by JB at 6/3/2008 3:31 PM

Thanks, that one got me
Gravatar # re: Root element is missing.
by Eric Lindberg at 6/16/2008 9:34 PM

Thanks, solved my problem too.
Gravatar # re: Root element is missing.
by Jon at 10/10/2008 4:32 PM

This was helpful... Thanks
Gravatar # re: Root element is missing.
by M at 12/10/2008 4:32 AM

You the man!
Gravatar # re: Root element is missing.
by FrankC at 12/13/2008 3:45 PM

Thanks a bunch, this worked nicely for me
Gravatar # re: Root element is missing.
by RL at 3/11/2009 12:52 PM

Hi folks,

Which file do I need to modify in order to fix the problem?

I'm very new to this .net stuff so I wouldn't know what to do.

thanks,
Gravatar # re: Root element is missing.
by Mark at 3/25/2009 1:45 PM

Excellent post man, thanks. This one got me too. Spent 15 minutes peering at the XML through watery eyes before I let Google do the work.
Gravatar # re: Root element is missing.
by fredrik at 10/5/2009 9:35 AM

Thanks, it works again. BING saved the day
Gravatar # re: Root element is missing.
by CF at 10/8/2009 3:01 PM

Thank you so much, kind sir.
Gravatar # re: Root element is missing.
by lostintrans at 11/23/2009 8:53 PM

Thanks a lot!!!
Post A Comment
Title:
Name:
Email:
Website:
Comment:
Verification: