Tuesday 29 September 2015

Unexpected XML declaration. The XML declaration must be the first node in the document

Once i was working with the XmlDocument in C#, i got something like this

Unexpected XML declaration. The XML declaration must be the first node in the document, and no white space characters are allowed to appear before it. Line 2, position 3.

Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.Xml.XmlException: Unexpected XML declaration. The XML declaration must be the first node in the document, and no white space characters are allowed to appear before it. Line 2, position 3.

Source Error:


Line 185:
Line 186:XmlDocument doc = new XmlDocument();
Line 187:doc.LoadXml(xmldata);
Line 188:
Line 189:

My clean code was

var  xmldataname = @"
<?xml version='1.0' encoding='utf-8'?>
<request>
<name>Raj</name>
</request>
";

XmlDocument doc = new XmlDocument();
doc.LoadXml(xmldata);

I went through http://stackoverflow.com/questions/13210458/unexpected-xml-declaration-white-space-not-allowed and whit i find they solved by clearing the StringBuilder, same technique i used for string and i changed my code as
       
var  xmldataname = @"<?xml version='1.0' encoding='utf-8'?>
<request>
<name>Raj</name>
</request>
";

XmlDocument doc = new XmlDocument();
doc.LoadXml(xmldata);


And it worked for me. :)