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
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)