What the error means
The XML declaration, <?xml version="1.0" ...?>, tells the parser which version and encoding to use. Because it configures how the rest of the file is read, the specification requires it to be the first thing in the document, with nothing before it — not a space, not a newline, not a comment. XML declaration after content means the parser had already read something when it reached the declaration.
In the example, a comment comes first. Comments are legal almost anywhere in XML, but not before the declaration.
Why it happens
- A comment or blank line inserted above the declaration, often by a build step that stamps generated files with a header.
- A byte-order mark (BOM). Some editors, and Windows tooling in particular, write an invisible three-byte marker at the start of UTF-8 files. Many parsers accept a BOM before the declaration, but not all, and a second BOM or one in an unexpected encoding produces this error.
- Two XML files concatenated, so the second file's declaration lands in the middle of the combined document.
- A template that emits the declaration after some literal output, or emits it twice.
- Leading whitespace from a copy that started one line too early.
How to fix it
- Paste the document into the formatter above. The error card gives the line of the declaration; everything above that line is the problem.
- Delete everything before
<?xml. If the declaration is on line one and the error persists, the file has an invisible character before it — see below. - If there are two declarations, keep the first and delete the second, and check whether two documents were joined by mistake; each needs its own file or a wrapping root element.
- Format again. The output starts with the declaration on line one.
The corrected example:
<?xml version="1.0" encoding="UTF-8"?>
<!-- generated by export job -->
<root/>
If it still fails
- Paste the first line into String Inspector. A BOM shows up as U+FEFF at index 0; a non-breaking space or zero-width space appears the same way. Remove it by re-saving the file as UTF-8 without BOM.
- If the declaration is generated by code, make sure it is the first write to the output stream, before any logging or header output.
- XML Validator reports the same condition with an error code and the exact column, which helps when the offending byte is invisible.
Related errors
Unclosed tag
Add the missing </element> for the start tag the parser names, or make an empty element self-closing with />. Every start tag needs exactly one matching end tag.
Mismatched closing tag
Close elements in the reverse order they were opened, and make the closing name match the opening name exactly, including case.