Skip to main content

Search 400 pages — tools, formats, elements, namespaces, directory, comparisons, XPath, datatypes, glossary, parse errors, schema errors, use cases, guides, blog and product.

XML guide

How to fix an invalid XML entity reference

Find the unescaped ampersand, distinguish named entities from character references, and repair the value without hiding malformed input.

6 min read · Updated 2026-08-21

The short answer

An ampersand starts an entity or character reference in XML, so a literal ampersand must be written as &. Fix the value at the serialization boundary, verify that every reference ends with a semicolon, and do not enable external-entity loading merely to make an unknown name resolve.

Locate the ampersand that starts no valid reference

The parser usually stops at the first raw ampersand in character data or an attribute. Query strings, company names, and copied HTML are common sources because they are valid text outside XML but not valid XML source spelling.

Malformed source spelling
<link>https://example.com/?page=1&sort=date</link>
Escaped XML
<link>https://example.com/?page=1&amp;sort=date</link>

Choose the correct XML spelling

XML predefines amp, lt, gt, quot, and apos. Numeric character references use decimal or hexadecimal code points. A project-specific named entity works only when a DTD declares it and the parser is configured to read that declaration.

  • Use &amp; for a literal ampersand and &lt; for a literal less-than sign in text.
  • Use &quot; or &apos; when the character would close the surrounding attribute quote.
  • Use &#169; or &#xA9; for a valid Unicode code point when a numeric reference is useful.
  • Do not copy HTML-only names such as &nbsp; into XML without a declaration.

Fix serialization instead of patching the document

If the XML is generated, escape values exactly once at the point they become XML text or attributes. Replacing every ampersand after serialization double-escapes existing references and can corrupt markup.

Keep external entity resolution disabled unless the application has a controlled, explicit need for it. An unknown entity is not a reason to broaden what the parser may fetch or read.

  • Preserve raw application values until the XML serializer writes them.
  • Test values containing &, <, both quote characters, and non-ASCII text.
  • Validate the complete output rather than checking individual replacement operations.

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.