Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Root element is missing

Tags:

c#

xml

asp.net

I am reading xml from xxx URl but i am getting error as Root element is missing.

My code to read xml response is as follows:

  XmlDocument doc = new XmlDocument();
  doc.Load("URL from which i am reading xml");
  XmlNodeList nodes = doc.GetElementsByTagName("Product");
  XmlNode node = null;
  foreach (XmlNode n in nodes)
   {
   }

and the xml response is as follows:

<All_Products>
   <Product>
  <ProductCode>GFT</ProductCode>
  <ProductName>Gift Certificate</ProductName>
  <ProductDescriptionShort>Give the perfect gift. </ProductDescriptionShort>
  <ProductDescription>Give the perfect gift.</ProductDescription>
  <ProductNameShort>Gift Certificate</ProductNameShort> 
  <FreeShippingItem>Y</FreeShippingItem>
  <ProductPrice>55.0000</ProductPrice>
  <TaxableProduct>Y</TaxableProduct>
   </Product>    
 </All_Products>

Can you please tell where i am going wrong.

like image 938
R.D. Avatar asked Apr 12 '12 14:04

R.D.


People also ask

What does it mean root element missing?

'The root element is missing' message is triggered when the Controller cache files are corrupt. There are several different potential causes for why these files to become corrupt.

What is a root element in XML?

The root element of an XML message is based on an object structure and an operation specified for the channel or service used for the communication. The root element can contain one or more attributes. The following table shows the attributes that can apply to root elements.


2 Answers

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); 
like image 159
Phil Avatar answered Oct 04 '22 02:10

Phil


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.

like image 28
coder Avatar answered Oct 04 '22 03:10

coder