XML Not Well-Formed? The Common Causes and How to Fix Each One
What "not well-formed", "mismatched tag" and "junk after document element" mean, the mistakes that cause them, and how to fix each one.
An XML file that looked fine is rejected with not well-formed (invalid token): line 1, column 8. Another parser says xmlParseEntityRef: no name about the same file, and a Java service says Content is not allowed in prolog. All three mean the document breaks one of XML's syntax rules, and the error message usually names the rule badly.
XML is strict on purpose. An HTML browser repairs broken markup and carries on; an XML parser is required to stop at the first well-formedness error and report it. That makes the errors frustrating, but it also means there is a short, fixed list of causes. This post goes through them with the messages two common parsers print: Python's xml.etree (built on expat) and xmllint (libxml2, also used by PHP and many Linux tools).
Pasting the document into the formatter below is a quick way to find structural problems such as mismatched or unclosed tags, because it reports the line and column instead of a generic failure. Re-indenting also makes nesting mistakes visible at a glance.
XML FormatterPaste XML to indent it readably or collapse it to one line, and to check that it is well formed. Errors point at the exact line and column. Everything runs in your browser, so nothing is uploaded.1. A bare & or < in text
This is the most common cause by far. In XML, & starts an entity reference and < starts a tag, so neither may appear as plain text:
<company>Smith & Sons</company>
<rule>price < 100</rule>
| Parser | Message |
|---|---|
| expat | not well-formed (invalid token): line 1, column 16 |
| libxml2 | xmlParseEntityRef: no name |
libxml2 (for <) | StartTag: invalid element name |
Escape them as & and <:
<company>Smith & Sons</company>
<rule>price < 100</rule>
The & problem usually comes from a URL with a query string, such as ?page=2&sort=name, or from a company or product name. Escape it in attributes too: href="/list?page=2&sort=name" is correct XML, and the parser hands your code the plain & back.
For a long block of text full of special characters, such as embedded code or HTML, a CDATA section avoids escaping altogether. Everything between <![CDATA[ and ]]> is treated as text:
<snippet><![CDATA[if (a < b && b < c) { return true; }]]></snippet>
The only thing a CDATA section cannot contain is its own terminator, ]]>.
2. HTML entities such as
XML defines exactly five named entities: &, <, >, " and '. Everything else that HTML knows, such as , © or é, is undefined unless a DTD declares it:
<name>Café Nero</name>
| Parser | Message |
|---|---|
| expat | undefined entity: line 1, column 9 |
| libxml2 | Entity 'eacute' not defined |
Use the character itself, which works in any UTF-8 document, or a numeric character reference, which works in any encoding:
<name>Café Nero</name>
<name>Café Nero</name>
  is the non-breaking space and © is the copyright sign. This error appears most often when HTML from a CMS or a rich-text editor is pasted into an XML feed.
3. Tags that do not match
Every start tag needs an end tag with exactly the same name, and elements must close in the reverse order they opened:
<item><name>Widget</item></name>
<Item>Widget</item>
| Parser | Message |
|---|---|
| expat | mismatched tag: line 1, column 20 |
| libxml2 | Opening and ending tag mismatch: name line 1 and item |
The second example fails because names are case-sensitive: <Item> and <item> are different elements. HTML is forgiving about both case and overlap, so markup copied from HTML is a frequent source.
Element names have rules of their own as well. A name cannot start with a digit, a hyphen or a period, and cannot contain spaces, so <1st-place> and <first place> are both errors. If the names come from data, such as column headers turned into tags, sanitize them first.
4. A tag that is never closed
<order>
<id>42</id>
<total>9.99</total>
| Parser | Message |
|---|---|
| expat | no element found: line 3, column 21 |
| libxml2 | Premature end of data in tag order line 1 |
The expat message is confusing because it points at the end of the file, not at the element that was left open. libxml2 names the element, which is more useful. Truncation is a common cause: a file cut off by a failed download, a size limit on a log line or a database column, or a process that crashed while writing.
Empty elements can be written either way, <br></br> or <br/>, but HTML-style <br> with no closing slash is an unclosed tag in XML.
5. More than one root element
An XML document has exactly one top-level element. Two of them side by side is an error:
<user id="1"/>
<user id="2"/>
| Parser | Message |
|---|---|
| expat | junk after document element: line 2, column 0 |
| libxml2 | Extra content at the end of the document |
This usually happens when records are appended to a file one at a time, or when two documents are concatenated. Wrap them in a single parent:
<users>
<user id="1"/>
<user id="2"/>
</users>
If the format really is one document per line, like a log, parse each line on its own instead of the whole file.
6. Anything before the XML declaration
The <?xml version="1.0"?> declaration is optional, but if it is present it must be the very first thing in the file. Not even a blank line or a space may come before it:
<?xml version="1.0" encoding="UTF-8"?>
<config/>
| Parser | Message |
|---|---|
| expat | XML or text declaration not at start of entity |
| libxml2 | XML declaration allowed only at the start of the document |
| Java (Xerces) | The processing instruction target matching "[xX][mM][lL]" is not allowed. |
Text before the root element without a declaration is also an error. Java reports it as Content is not allowed in prolog, and that message has a well-known hidden cause: something that is not XML at all at the start of the input. Common culprits are a leading newline from a template engine, an HTML error page returned where XML was expected, or a stray character from a bad copy and paste. If the input comes from an HTTP response, log the first few bytes before parsing.
7. Attribute mistakes
XML attributes must have a value, and the value must be in quotes. HTML allows both of these; XML allows neither:
<input type=checkbox checked>
Each attribute may appear only once per element, and the value may not contain a raw <:
<a href="/x" href="/y"/>
<rule test="a < b"/>
| Mistake | expat | libxml2 |
|---|---|---|
| Unquoted value | not well-formed (invalid token) | AttValue: " or ' expected |
| Duplicate attribute | duplicate attribute | Attribute href redefined |
< in value | not well-formed (invalid token) | Unescaped '<' not allowed in attributes values |
The fixes are checked="checked", removing the duplicate, and test="a < b". A quote character of the same kind as the delimiter must also be escaped: title="say "hi"", or use single quotes around the value instead.
Finding the error in a large file
Line and column numbers count from the start of the document the parser was given. If your code wraps or modifies the XML before parsing, for example by adding a header, the numbers will not match the file on disk.
A few habits make large files manageable:
- Validate from the command line.
xmllint --noout file.xmlprints nothing if the file is well-formed, and the error with a line number and a caret if not. Python'spython3 -c "import xml.etree.ElementTree as E; E.parse('file.xml')"does the same. - Look just before the reported position. The parser reports where it noticed the problem, which can be after the actual mistake. An unclosed tag, in particular, is only detected at the end of its parent or of the file.
- Fix the first error first. Parsers stop at the first error, and a single missing
>can make everything after it meaningless. - Re-indent. Once a file is well-formed, formatting it shows nesting mistakes that are valid XML but wrong for your schema, such as an element closed one level too early.
Well-formed is the minimum. A document can pass every check in this post and still be rejected for not matching its schema (XSD), such as a required element missing or a number where a date was expected. That is validation, a separate step that needs the schema file.
Quick reference
| Message (expat / libxml2) | Usual cause | Fix |
|---|---|---|
not well-formed (invalid token) / xmlParseEntityRef: no name | Bare & in text or attribute | & |
not well-formed (invalid token) / StartTag: invalid element name | Bare < in text, or a name starting with a digit | <, or rename the element |
undefined entity / Entity '...' not defined | HTML entity like | The character itself or   |
mismatched tag / Opening and ending tag mismatch | Overlapping tags or different case | Close in reverse order, match case |
no element found / Premature end of data | Unclosed element or truncated file | Close it, or re-fetch the file |
junk after document element / Extra content at the end | Two root elements | Wrap in one parent |
XML or text declaration not at start | Whitespace before <?xml | Delete everything before it |
duplicate attribute / Attribute ... redefined | Same attribute twice | Remove one |
