Root element is missing Root element is missing xml xml

Root element is missing


Just in case anybody else lands here from Google, I was bitten by this error message when using XDocument.Load(Stream) method.

XDocument xDoc = XDocument.Load(xmlStream);  

Make sure the stream position is set to 0 (zero) before you try and load the Stream, its an easy mistake I always overlook!

if (xmlStream.Position > 0){    xmlStream.Position = 0;}XDocument xDoc = XDocument.Load(xmlStream); 


Make sure you XML looks like this:

<?xml version="1.0" encoding="utf-8"?><rootElement>...</rootElement>

Also, a blank XML file will return the same Root elements is missing exception. Each XML file must have a root element / node which encloses all the other elements.


Hi this is odd way but try it once

  1. Read the file content into a string
  2. print the string and check whether you are getting proper XML or not
  3. you can use XMLDocument.LoadXML(xmlstring)

I try with your code and same XML without adding any XML declaration it works for me

XmlDocument doc = new XmlDocument();        doc.Load(@"H:\WorkSpace\C#\TestDemos\TestDemos\XMLFile1.xml");        XmlNodeList nodes = doc.GetElementsByTagName("Product");        XmlNode node = null;        foreach (XmlNode n in nodes)        {            Console.WriteLine("HI");        }

As stated by Phil in below answer please set the xmlStream position to zero if it is not zero.

if (xmlStream.Position > 0){    xmlStream.Position = 0;}XDocument xDoc = XDocument.Load(xmlStream);