Fixing .NET Exception “System.Xml.XmlException: The data at the root level is invalid. Line 1, position 1.”

This article describes a workaround to the importunate .NET exception “System.Xml.XmlException: The data at the root level is invalid. Line 1, position 1.”

The following .NET exception is usually thrown if you try to load and parse an XML stream/file starting with a BOM (byte-order mark):

System.Xml.XmlException: The data at the root level is invalid. Line 1, position 1.

BOM is a Unicode character that indicates the nature and endianness (byte-order) of a text file or stream. In most cases, there is an ASCII 65279 or Unicode U+FEFF aka zero-width no-break space (ZWNBSP) right at the beginning of the XML file or stream.

The most common byte-order marks:

  •  (EF BB BF): UTF-8
  • þÿ (FE FF): UTF-16 Big-Endian
  • ÿþ (FF FE): UTF-16 Little-Endian
  • □□þÿ (00 00 FE FF): UTF-32 Big-Endian
  • ÿþ□□ (FF FE 00 00): UTF-32 Little-Endian
Solution

To solve this problem, you need to remove the BOM from the start of the XML stream:

int gtIndex = xmlString.IndexOf('<');
if (gtIndex > 0)
  xmlString = xmlString.Remove(0, gtIndex); // Remove any byte-order mark (BOM)

4 thoughts on “Fixing .NET Exception “System.Xml.XmlException: The data at the root level is invalid. Line 1, position 1.”

  1. Thanks for your Post. I have been going crazy trying to get a vbscript to invoke a web services. The BOM was causing the problem. The solution for vb is to use a System.IO.SteamReader to load the file. This removes the BOM.

Leave a Reply to Matt Paisley Cancel reply

Your email address will not be published. Required fields are marked *

*