Smart Systems for Home

Plain how-to guides for smart home, security and home Wi-Fi

PostgreSQL 2200M Invalid XML Document: Fix Guide

· 7 min read · Home Tech

In this article
  1. What You'll Need
  2. Step-by-Step
  3. Common Mistakes
  4. Tips
  5. Troubleshooting
  6. Frequently Asked Questions

Error code 2200M means the XML value you sent to PostgreSQL failed validation: the parser could not build a well-formed document from the text you handed it. It is not a permissions or connection problem, and it does not mean PostgreSQL is broken. Fix it by finding the exact row or statement that fails, dumping the raw text, and running it through an XML parser outside the database. Once you can see the character or tag that breaks the document, the fix is usually a data cleanup or an escaping change in your application, not a server setting.

This error appears anywhere PostgreSQL parses XML for you: inserting into an xml column, casting text with ::xml, calling XMLPARSE, or evaluating xpath() and related XPath functions. The error text normally names the reason, something like invalid XML document followed by a parser detail. Labels in client tools and admin panels can differ slightly by version, but the SQL objects and function names below are stable across current PostgreSQL releases.

What You'll Need

  • A PostgreSQL user that can read the affected table and run SELECT queries against it.
  • A client that shows the full error message, not just the code: psql, pgAdmin, DBeaver or similar. Truncated messages hide the parser detail you need.
  • The original XML text from the source system, if you can get it, so you can compare what was sent with what was stored.
  • An XML validator you trust: a browser tab that opens local XML files, a command line tool such as xmllint, or your editor's XML plugin. This is for diagnosis, not for the database.
  • Write access to the affected table only when you are ready to correct data, and a backup or a copy of the affected rows first.

Step-by-Step

  1. Read the whole error, not just the code. A typical message looks like ERROR: invalid XML document followed by DETAIL and LINE lines. The detail often says whether the problem is an unclosed tag, a bad character reference, extra content after the root element, or a declaration issue. Write down the detail text; it narrows the search to a few characters.
  2. Identify the statement or row that fails. If the error came from an INSERT or UPDATE, isolate it by running the same literal through SELECT XMLPARSE(DOCUMENT '...') in your client. If it came from a batch load, check your import logs for the row number, then find that row in the source file. If it came from a query over existing rows, the error is in stored data and you need a scan (next step).
  3. Re-run the input in a validator. Save the exact bytes to a file with UTF-8 encoding and open or validate it. A validator reports the line and column, which is far more useful than the database's position hint, especially for long documents. If the validator accepts it but PostgreSQL rejects it, the difference is usually an encoding or whitespace issue introduced in transit.
  4. Check for the five usual causes. Unescaped & characters (a bare ampersand starts an entity reference and must be &amp;), unescaped < in text, mismatched or unclosed tags, missing root element or two root elements, and leading whitespace before the XML declaration. All five are extremely common in hand-built strings.
  5. Check the character set. XML must be encoded in a character set you declare correctly, and PostgreSQL parses it as UTF-8 unless told otherwise. If your application sends Windows-1252 bytes that contain characters outside ASCII, the parser sees invalid byte sequences. Convert the data to UTF-8 before it reaches the database and, if you use an encoding declaration, make sure it says UTF-8.
  6. Check for control characters and null bytes. Characters that are not legal in XML at all (many low control characters, form feed, and embedded nulls) cannot be represented even escaped. Strip or replace them in the source data. This is the most common cause of failures in XML produced by scraping or logging pipelines.
  7. Check for content after the root element. Concatenating two fragments, or appending a log line to a document, produces multiple root nodes, which is never valid. Wrap fragments in a single container element if you genuinely need to store them together.
  8. Fix the source, not just the row. Correcting one row leaves the pipeline that generated it intact, and it will fail again on the next batch. Add validation in your application before the database, or build the XML with a library function such as XMLSERIALIZE, XMLELEMENT and XMLFOREST, which escape content for you.
  9. Repair existing bad rows deliberately. Find them with a query that tolerates failure per row, for example a SELECT that extracts the suspect column and a filter you can narrow down, then copy the offending rows into a scratch table before updating. Never run a broad UPDATE against a production table without first testing the same statement on a copy and confirming the row count.
  10. Confirm SQLSTATE behaviour. The xml type validates on input, so the error surfaces at write time, not at read time. If writes must accept messy text, store it in a text column and validate later with a check or a job, rather than weakening validation you rely on elsewhere.

Common Mistakes

  • Assuming it is a server problem. 2200M is data validation. Restarting PostgreSQL or raising limits changes nothing.
  • Fixing one row and closing the ticket. The generator keeps producing the same malformed document. Fix the producer as well.
  • Hand-escaping ampersands. Double-escaping (&amp;amp;) turns a working value into a literal &amp; in the stored document, which parses but is wrong. Use a library or the built-in XML constructor functions.
  • Trusting the client's display of the string. Many clients normalise line endings, hide control characters, or silently re-encode text. Look at the bytes in a hex viewer when the visible text looks fine.
  • Using string concatenation to build XML. Any unescaped value from a form or API response will eventually contain & or < and break the document.
  • Ignoring the encoding declaration. A declaration that says one encoding while the bytes are another is a guaranteed parse failure.

Tips

  • When testing, always run the failing input through SELECT XMLPARSE(DOCUMENT ...) before touching a table. It isolates the parser from everything else.
  • Keep a copy of the raw failing input in a text column next to the converted value during rollout, so a failure can be reproduced without guesswork.
  • Normalise incoming XML to UTF-8 at the earliest point in your pipeline. Every downstream tool, including PostgreSQL, then has one less variable.
  • If your source produces fragments rather than full documents, wrap them consistently in one root element at the boundary, so the database always receives a document.
  • Add a validation step to your import script that runs before the database transaction starts, so bad batches never partially load.

Troubleshooting

The validator accepts the file but PostgreSQL still rejects it. Compare byte for byte. Common culprits are carriage returns before the declaration, a BOM inserted by an editor, or the client converting the string to another encoding. Re-save as UTF-8 without BOM and retry.

You cannot find the bad row. Narrow the search: filter by length, by a substring you know appears in dirty records, or by time imported. Extract the values to files in small batches and run them through a validator to identify which ones fail.

The error only appears in one client. That client is probably changing the text, for example converting newlines or trimming whitespace. Test with psql using a here-document or a file to bypass client transformation.

The document contains valid-looking XML from a third party. Ask their exports to be UTF-8 and confirm they do not concatenate multiple documents per file. Batch files with several root-level documents are a frequent cause.

If that did not work: capture the exact SQL statement, the input bytes, the PostgreSQL version and the full error detail, then reproduce on a copy of the table. If the input parses in an external validator and the same literal parses through XMLPARSE, the problem lies in how the application sends it, and that is where to instrument next.

Frequently Asked Questions

Is SQLSTATE 2200M the same as malformed XML?

Yes. It is the class 22 data exception for an invalid XML document. The detail line names the specific parser complaint.

Does PostgreSQL accept XML fragments?

Yes, through XMLPARSE(CONTENT ...) and the xml type, but XMLPARSE(DOCUMENT ...) requires exactly one root element. Choose deliberately, because DOCUMENT is stricter.

Can I disable XML validation?

Not on the xml type; validation happens on input. Store the text in a text column if you must accept unvalidated content, and validate separately.

Why does it fail only for some users' data?

Names, addresses and free-text fields often contain ampersands and angle brackets. Inputs without those characters parse fine, which is why the error appears only on specific records.

Does collation or locale affect this?

No. XML parsing is about bytes, encoding and structure, not collation. Changing the database collation will not fix 2200M.

Will upgrading PostgreSQL fix it?

No. The parser is rejecting genuinely invalid input. The fix is in the data or the code that produces it.