Unexpected XML declaration

An XML declaration (<?xml …?>) appears somewhere other than the very start.

The message, as .NET reports it
Unexpected XML declaration. The XML declaration must be the first node in the document, and no whitespace characters are allowed to appear before it. Line 2, position 3.

Why it happens

  • Whitespace or a blank line before <?xml, often from a verbatim string (@" followed by a line break) or a template.
  • Two documents concatenated.

How to fix it

Trim the input before parsing (xml.TrimStart()), or remove the second declaration when combining documents.

.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 XML declaration allowed only at the start of the document. It checks the whole document in your browser and lists every schema error with its line and column, not only the first.

XML declaration allowed only at the start of the document

Example

Reports the error

<?xml version="1.0"?>
<note/>
Fixed
<?xml version="1.0"?>
<note/>