Skip to main content

XML error · prolog

XML declaration allowed only at the start of the document

Whitespace precedes the XML declaration. A single blank line, or one space, before it is enough to make the document not well-formed.

XML declaration allowed only at the start of the document (line 2)

What it means

The XML declaration must be the very first thing in the document — not one space, not one newline. This is stricter than the rule for content before the root element, where whitespace is fine.

Because the offending bytes are invisible in most editors, this is a famously confusing error: the file looks correct and still fails. If the leading bytes are printable text rather than whitespace, you get "Start tag expected" instead.

One nuance worth knowing: a UTF-8 byte-order mark alone does not trigger this. libxml2 — and so XMLDir — tolerates a leading BOM, while Xerces and .NET reject it as content in the prolog. A file that validates here can still fail in a Java or .NET pipeline, so save without a BOM regardless.

What usually causes it

  • A blank line or trailing whitespace before <?xml, often left by an include or a template.
  • Output echoed before the declaration — a debug print, a warning, or a newline after PHP's closing ?> tag.
  • Concatenating two XML documents, so a second declaration appears mid-file.
  • A UTF-8 byte-order mark, which other parsers reject even though this one accepts it.

How to fix it

  • Remove all whitespace before the declaration; it must start at byte zero.
  • Save as UTF-8 without BOM. In PowerShell prefer Out-File -Encoding utf8 over Set-Content's ANSI default.
  • Check the first bytes directly: xxd file.xml | head -1.
  • Omit PHP's closing ?> tag so a trailing newline cannot leak into the output.

The same error elsewhere

Different parsers, same defect. If you arrived with one of these messages, you are in the right place.

  • Xerces (Java)

    Content is not allowed in prolog.
  • expat (Python)

    XML or text declaration not at start of entity: line 2, column 0
  • .NET System.Xml

    Data at the root level is invalid. Line 2, position 1.

Before and after

Both snippets are re-checked by the test suite against the real parser: the first is confirmed to produce the exact error above, the second to parse cleanly.

Fails

<?xml version="1.0" encoding="UTF-8"?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"/>
Parses
<?xml version="1.0" encoding="UTF-8"?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"/>

Where this bites most

Get started

Bring order to the XML your team can't afford to ignore.

Create a free account and get a private workspace to search, validate, diff, and monitor your XML feeds, sitemaps, schemas, and vendor integrations.