Tuesday, September 21, 2010

Data at the root level is invalid. Line 1, position 1



Problem:

The problem is that strings are stored internally as UTF-16 in .NET however the encoding specified in the XML document header may be different. E.g.:


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



              Each Unicode character in a string is defined by a Unicode scalar value, also called a Unicode code point or the ordinal (numeric) value of the Unicode character. Each code point is encoded using UTF-16 encoding, and the numeric value of each element of the encoding is represented by a Char object.

This means that when you pass XmlDocument.LoadXml() your string with an XML header, it must say the encoding is UTF-16. Otherwise, the actual underlying encoding won't match the encoding reported in the header and will result in an XmlException being thrown.


Solution:

The solution for this problem is to make sure the encoding used in whatever you pass the Load or LoadXml method matches what you say it is in the XML header. In my example above, either change your XML header to state UTF-16 or to encode the input in UTF-8 and use one of the XmlDocument.Load methods instead of XmlDocument.LoadXML method.

XmlDocument xmlDocument = new XmlDocument();
xmlDocument.Load(ConfigurationManager.AppSettings["CatalogXMlRootPath"] + Catalog + ".xml");
return xmlDocument;


Check list:

  • Check the given xml file having any unclosed tags
  • Check wheather xml file starting line having any empty line.
  • have you given enough permission to xml folder
  • Use xmldocument.Load instead of LoadXMl method

No comments:

Post a Comment