Skip to main content

XML error · InvalidChar

Character is not expected

A raw character appeared where markup was required — most often an unescaped ampersand.

char '&' is not expected.

What it means

Five characters cannot appear literally in XML content. The ampersand is the one that breaks real documents, because it starts an entity reference: the parser sees & and expects a name and a semicolon to follow.

This is the single most common failure in generated sitemaps and feeds, because URLs with query strings contain ampersands and string interpolation does not escape them.

What usually causes it

  • An unescaped & in a URL query string: ?a=1&b=2 instead of ?a=1&b=2.
  • A literal < or > in text content rather than &lt; and &gt;.
  • Text before the root element — a stray log line, a PHP notice, or a byte-order mark.
  • HTML entities XML does not define, such as &nbsp;, in a document with no DTD.
  • Double-escaping fixes applied on top of already-escaped output.

How to fix it

  • Escape the five predefined entities: &amp; &lt; &gt; &quot; &apos;.
  • Escape URLs when writing them into XML, even though they are already URL-encoded.
  • Use a numeric reference (&#160;) instead of a named HTML entity like &nbsp;.
  • Wrap HTML bodies in CDATA rather than escaping them character by character.
  • Check for output printed before the XML declaration — that is content in the prolog, not a content bug.

The same error elsewhere

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

  • libxml2 (PHP, lxml, Nokogiri)

    xmlParseEntityRef: no name
  • Xerces (Java)

    The reference to entity "page" must end with the ';' delimiter.
  • expat (Python)

    not well-formed (invalid token): line 2, column 40
  • .NET System.Xml

    An error occurred while parsing EntityName.

Before and after

Both snippets are checked on every build: the first is confirmed to produce the error above, the second to parse cleanly.

Fails
<url>
  <loc>https://example.com/search?q=xml&page=2</loc>
</url>
Parses
<url>
  <loc>https://example.com/search?q=xml&amp;page=2</loc>
</url>

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.