tags:

views:

47

answers:

3

Hello

I'm having the following code which is spitting 'Root Element Missing' during doc.Load().

MemoryStream stream = new MemoryStream();
XmlTextWriter xmlWriter = new XmlTextWriter(stream, Encoding.UTF8);
xmlWriter.Formatting = System.Xml.Formatting.Indented;
xmlWriter.WriteStartDocument();
xmlWriter.WriteStartElement("Root");
XmlDocument doc = new XmlDocument();
stream.Position = 0;
doc.Load(stream);
xmlWriter.Close();

I'm not able to figure out the issue. Any insights?

+4  A: 

You haven't flushed the xmlWriter, so it may well not have written anything out yet. Also, you're never completing the root element, so even if it has written out

<Root>

it won't have written the closing tag. You're trying to load it as a complete document.

I'm not sure at what point an XmlWriter actually writes out the starting part of an element anyway - don't forget it may have attributes to write too. The most it could write out with the code you've got is <Root.

Here's a complete program which works:

using System;
using System.IO;
using System.Text;
using System.Xml;

class Test
{
    static void Main(string[] args)
    {
        using (MemoryStream stream = new MemoryStream())
        {
            XmlTextWriter xmlWriter = new XmlTextWriter(stream, Encoding.UTF8);
            xmlWriter.Formatting = System.Xml.Formatting.Indented;
            xmlWriter.WriteStartDocument();
            xmlWriter.WriteStartElement("Root");
            xmlWriter.WriteEndElement();
            xmlWriter.Flush();

            XmlDocument doc = new XmlDocument();
            stream.Position = 0;
            doc.Load(stream);
            doc.Save(Console.Out);
        }
    }
}

(Note that I'm not calling WriteEndDocument - that only seems to be necessary if you still have open elements or attributes.)

Jon Skeet
Point of order: is .Close() not usually more correct than .Flush()?
annakata
@annalata: I assume that would close the stream, which we don't want to do here. Usually I would just dispose the writer though.
Jon Skeet
A: 

What @Skeet said, plus, you don't seem to close your element:

xmlWriter.WriteEndElement();
Robaticus
I covered that in my second sentence :)
Jon Skeet
Indeed you did, but in *stealth mode* -- that's the only reason I could comprehend as to why I would have missed it. :)
Robaticus
A: 

Well I see you starting the document, but I don't see you ending it or closing it... (at least not before you use it)

annakata