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.

Your comment:

Title:
Name:
Email:
Website:
 
Italic Underline Blockquote Hyperlink
 
 
Please add 5 and 2 and type the answer here: