Data at the root level is invalid

The input does not start with markup: it is not XML, or something comes before the root element.

The message, as .NET reports it
Data at the root level is invalid. Line 1, position 1.

Why it happens

  • A file path passed to XmlDocument.LoadXml(), which expects the XML text itself; use Load() for a path or stream.
  • The input is not XML: an HTML error page, JSON, or a server message.
  • Bytes before the first <: a byte order mark in a string read with the wrong encoding, or text before the root.

How to fix it

Check what you pass: LoadXml and XDocument.Parse take XML text, Load takes a path, URI or stream. Then look at the first characters of the input; for a stream, let XmlReader detect the encoding instead of decoding it yourself.

.NET throws an XmlSchemaValidationException at the first schema error unless XmlReaderSettings.ValidationEventHandler is set, which then receives every one with its line and position. A well-formedness error is an XmlException and ends reading whatever the settings.

The same problem in xmlvalid

xmlvalid validates with libxml2, which reports it as Start tag expected, '<' not found. It checks the whole document in your browser and lists every schema error with its line and column, not only the first.

Start tag expected, '<' not found

Example

Reports the error
hello <note/>
Fixed
<note>hello</note>