If anyone can explain why I\'m getting a \"Root element is missing\" error when my XML document (image attached) has a root element, they win a pony which fires lazers from
Your problem is due to this line:
xml = reader.ReadToEnd();
This positions the reader stream to the end so that when XmlReader.Create
is executed, there is nothing left in the stream for it to read.
If you need the xml
string to be populated, then you need to close and reopen the reader prior to XmlReader.Create
. Otherwise, removing or commenting this line out will solve your problem.
I ended up creating a quick little function to reference before each new XmlReader...
private void ResetStream()
{
/*
The point of this is simply to open the stream with a StreamReader object
and set the position of the stream to the beginning again.
*/
StreamReader reader = new StreamReader(m_stream);
if (reader != null)
{
reader.BaseStream.Position = 0;
}
}
So when I'm working in xml I call it right before I create my reader. I always have the same stream in memory and never recreate that.
ResetStream();
using (XmlReader reader = XmlReader.Create(m_stream)) { reader.Read(); }
Reset the base stream's position each time it is read if you want to read from the beginning as stated earlier, but you don't have to re-create the stream each time.
String xmlResource = Assembly.GetExecutingAssembly().GetName().Name + ".XML.IODeleter.xsd";
configXsd = new StreamReader(Assembly.GetExecutingAssembly().GetManifestResourceStream(xmlResource));
if (configXsd != null)
{
configXsd.BaseStream.Position = 0;
File.WriteAllText(apppath + @"\" + Assembly.GetExecutingAssembly().GetName().Name + ".XML.IODeleter.xsd", configXsd.ReadToEnd());
}