# Unexpected XML declaration

Source: https://xmlvalid.com/errors/unexpected-xml-declaration

> An XML declaration (…?) 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

libxml2, which xmlvalid validates with, reports it as [XML declaration allowed only at the start of the document](https://xmlvalid.com/errors/xml-declaration-allowed-only-at-the-start): `XML declaration allowed only at the start of the document`

## Example that fails

```xml

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

## Fixed

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