How do I fix "XML parsing error: not well-formed"?

Dark navy cover card with the title 'How do I fix "XML parsing error: not well-formed"?' in white and a green accent bar

The XML parsing error "not well-formed" means the document breaks one of XML's basic syntax rules, so the parser stops reading. To fix it, go to the line and column in the message and look for a bare & or < in text, a tag that isn't closed or doesn't match, or something in front of the <?xml ?> declaration.

What "XML parsing error: not well-formed" means

The XML parsing error "not well-formed" is a fatal error: the file doesn't follow the grammar in the XML 1.0 specification. The spec defines a fatal error as one a conforming processor "MUST detect and report", and it says the processor must not carry on with normal processing after that.

So you get nothing. A browser won't render half a feed, and a Python script won't hand you a partial tree. One bad character anywhere breaks the whole document.

The wording changes with the tool:

XML Parsing Error: not well-formed
Location: https://example.com/feed.xml
Line Number N, Column M:
xml.etree.ElementTree.ParseError: not well-formed (invalid token): line N, column M

Firefox prints the first form with a caret under the bad spot. Python's ElementTree ParseError has a position attribute, "A tuple of line, column numbers, specifying where the error occurred", plus a code from the expat parser.

Find the exact line and column first

The line and column in the message are the fastest way to the fix, so open the raw file before you change anything. Look at the character the column points to, and at the one just before it.

  • Open the raw source, not a page the browser has already rendered. In a browser, use view-source on the URL.
  • If the file looks fine on disk but fails over HTTP, check the bytes the server sent. The problem is in what is served, not in your editor.
  • Look a little earlier. Parsers often report an unclosed quote or tag where they finally give up, further down the file.

The common causes and their fixes

The same five rule breaks cause nearly every "not well-formed" error.

What the parser points at XML rule broken Fix
A & in text, like Tom & Jerry & must be escaped Write &amp;
A < in text, like a < b < must be escaped Write &lt;
The very start of the file Declaration must come first Remove spaces, blank lines or a BOM issue before <?xml
An end tag End tag name must match the start tag Close tags in the reverse order you opened them
An attribute Each attribute name only once per tag Remove the duplicate
A strange invisible character Not in XML's allowed Char range Strip control characters, fix the encoding

Bare ampersands and angle brackets

A bare & or < is the most common cause of this error. The spec, section 2.4, says the ampersand and the left angle bracket "MUST NOT appear in their literal form" except as markup or inside a comment, a processing instruction or a CDATA section. Elsewhere they must be written as &amp; and &lt;, or as numeric character references.

A typical failure: a product title from a database goes straight into the XML.

<item>
  <title>Salt & Pepper Shakers</title>
</item>

The parser stops at the space after &. It expected an entity name like amp;. Fixed:

<item>
  <title>Salt &amp; Pepper Shakers</title>
</item>

A PHP bug report about a parser failing on a bare & in a title field was closed as "not a bug", because the & has to be written as &amp;. The fix belongs where the XML is generated: use your language's XML library to write text nodes instead of joining strings.

XML has five predefined entities that every processor must recognise: amp, lt, gt, apos and quot (section 4.6). HTML names such as &nbsp; or &copy; are not among them, so they fail too unless a DTD declares them. Use a numeric reference instead.

Anything before the XML declaration

The XML declaration has to be the first thing in the file. The spec's grammar puts the optional <?xml ... ?> declaration at the very start, and the name xml is reserved for it. If a blank line, a space or an echoed debug message comes first, the parser sees a processing instruction named xml in the wrong place.

The W3C Feed Validator's notes on this error list whitespace before the declaration as a common cause. In PHP and WordPress feeds this is often a blank line after a closing ?> in some included file.

Tags that don't match or aren't closed

Every end tag has to match its start tag, and tags have to close in reverse order. The spec rule reads: "The Name in an element's end-tag MUST match the element type in the start-tag." XML names are case-sensitive, so <Price> closed with </price> fails.

<order><total>ten</order></total>

That line fails because total is still open when </order> arrives. The document also needs exactly one root element, so two top-level elements side by side is another version of the same error.

Duplicate attributes and unquoted values

A start tag can't repeat an attribute. The spec's "Unique Att Spec" rule says an attribute name "MUST NOT appear more than once in the same start-tag". Attribute values also need quotes, single or double, so <item id=4> fails where <item id="4"> works.

Invalid characters and wrong encoding

Some characters are banned from XML altogether. The Char rule in section 2.2 allows tab, line feed and carriage return, then everything from #x20 up, with a few gaps. That leaves out most control characters, like the form feed or a stray \x08 backspace pasted from a terminal.

Encoding causes the same "invalid token" message. If the file says encoding="UTF-8" but contains bytes saved as Windows-1252, a curly quote or an é becomes an illegal byte sequence. Re-save the file in the encoding it declares, or fix the declaration.

When CDATA is the right fix

A CDATA section lets you keep & and < as they are. Section 2.7 says that inside CDATA "only the CDEnd string is recognized as markup", and the CDEnd string is ]]>.

<script><![CDATA[ if (a < b && c) { run(); } ]]></script>

CDATA suits blocks of code or HTML you'd rather not escape character by character. It breaks when the text itself contains ]]>, and it does nothing for control characters, which are banned everywhere.

My take: escape by default and use CDATA only for embedded code. Escaping through a real XML library is harder to get wrong, and it's what the PHP maintainers pointed people to.

Why JavaScript try/catch doesn't catch it

In the browser, DOMParser doesn't throw on bad XML. According to MDN's parseFromString page, if the input isn't well-formed, "the returned document will contain a node describing the nature of the parsing error." A TypeError is thrown only for a disallowed MIME type.

So this code never reaches the catch:

try {
  const doc = new DOMParser().parseFromString(text, "application/xml");
  console.log(doc.documentElement.nodeName);
} catch (e) {
  console.log("never runs for bad XML");
}

Check for the error element instead:

const doc = new DOMParser().parseFromString(text, "application/xml");
const err = doc.querySelector("parsererror");
if (err) throw new Error(err.textContent);

The parsererror text contains the same "not well-formed" message and the position. Skip this check and your app will happily treat an error document as data.

Checking a file quickly in the browser

The OnlineViewer XML viewer runs your XML through the browser's own DOMParser and shows the parsererror text when the file is broken. The XML stays in the page and isn't uploaded anywhere, which matters when it holds customer data.

The limitation: a browser parser only checks well-formedness. It won't tell you whether the file matches a DTD or XSD, and parsers disagree on edge cases. A Mozilla bug report notes that Firefox's parser predates the 5th edition name rules, so a rare element name can fail in Firefox but pass elsewhere.

Once the XML parses, read what an XML file is and how it is formatted, convert the XML to JSON, or see how XML attributes map to JSON. The JSON version of this problem is Unexpected end of JSON input.

FAQ

What does 'not well-formed (invalid token)' mean?

The parser hit a character it can't accept at that spot. The usual culprits are a bare & or < in text, a control character, or a byte in the wrong encoding.

How do I escape an ampersand in XML?

Write & instead of &. Use < for <. Inside a CDATA section you can leave both as they are.

Can whitespace before <?xml break a file?

Yes. The XML declaration has to come first, so a blank line, space or stray text in front of it makes many parsers reject the file.

Why does my JavaScript try/catch not catch the XML error?

DOMParser.parseFromString doesn't throw on bad XML. It returns a document that contains a element, so you have to check for that element yourself.

Is well-formed the same as valid XML?

No. Well-formed means the syntax is correct. Valid means it is well-formed and also matches a DTD or schema. This error is only about syntax.

Sources