Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"Root element is missing" error but I have a root element

Tags:

c#

xml

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 its eyes.

enter image description here

Code:

if (ISF.FileExists("Players.xml")) {     string xml;     using (IsolatedStorageFileStream rawStream = ISF.OpenFile("Players.xml", FileMode.Open))     {         StreamReader reader = new StreamReader(rawStream);         xml = reader.ReadToEnd();           XmlReaderSettings settings = new XmlReaderSettings { IgnoreComments = true, IgnoreWhitespace = true };         XmlReader xmlReader = XmlReader.Create(reader, settings);          while (xmlReader.Read())         {             switch (xmlReader.NodeType)             {                 case XmlNodeType.Element:                     switch (xmlReader.Name)                     {                         case "numberOfPlayers":                             string nodeValue = xmlReader.ReadContentAsString();                             int NODEVALUE = int.Parse(nodeValue);                             MessageBox.Show(" " + NODEVALUE);                             break;                     }                     break;             }             break;         }         reader.Close();     } } 
like image 832
dannybrown Avatar asked Dec 10 '11 02:12

dannybrown


People also ask

What does it mean when it says root element is missing?

The message 'Root element is missing' can most likely occur when an XML data file has been corrupted on your system.

Is root element mandatory in XML?

An XML document must have a single root element, which contains all other XML elements in the document.

Can XML have more than one root element?

While a properly formed XML file can only have a single root element, an XSD or DTD file can contain multiple roots. If one of the roots matches that in the XML source file, that root element is used, otherwise you need to select one to use.


1 Answers

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.

like image 83
competent_tech Avatar answered Oct 05 '22 23:10

competent_tech