PostgreSQL Error 2200N: Invalid XML Content Fix
In this article
PostgreSQL error 2200N means the XML value you tried to store or process is not well-formed according to the XML 1.0 specification. The fix is to find the offending row or input, correct the malformed XML (unclosed tags, stray ampersands, invalid characters), and re-run the statement. You cannot suppress this error with a setting: PostgreSQL validates XML on input, so the data itself must be valid.
What You'll Need
- Access to the PostgreSQL database with a role that can read the affected table and run queries (psql, pgAdmin, DBeaver, or your application's SQL console).
- The exact SQL statement or application code path that triggers the error, including the parameter values being sent.
- An XML validation tool or parser (xmllint, a browser, or your language's XML library) to test candidate fixes before writing them back.
- Write access to the application code or ETL job if the malformed XML is generated upstream rather than stored already.
Step-by-Step
- Read the full error message. PostgreSQL returns something like
ERROR: invalid XML contentwith aDETAILline naming the specific problem, for exampleline 3: Opening and ending tag mismatch: item line 3 and itemsorEntityRef: expecting ';'. Copy the DETAIL text; it tells you the line and character position inside the XML document. Labels in client tools can differ slightly by version, but the server message text is consistent. - Identify which statement or row is failing. If the error comes from an INSERT or UPDATE, isolate it by running the statement with a single row at a time. If it comes from a SELECT that calls
xmlelement,xmlforest,xmlagg, or casts text toxml, comment out parts of the query until the failing expression is obvious. For bulk loads, check the COPY or ETL log for the row number. - Reproduce the failure in isolation. Run
SELECT '<your xml here>'::xml;in psql with the exact string that failed. This confirms whether the problem is the XML itself or something the query does to it. If the literal cast succeeds but the table insert fails, the problem is in a trigger, a generated column, or a constraint that transforms the value. - Validate the XML with an external parser. Save the string to a file and run
xmllint --noout file.xml. xmllint reports the same class of problems PostgreSQL does and often gives clearer line numbers. Fix each reported issue in turn, re-running xmllint until it exits silently. - Fix the common causes. The overwhelming majority of 2200N errors come from four things: unescaped ampersands (use
&), unescaped angle brackets in text (use<and>), unclosed or mismatched tags, and invalid control characters such as a raw NUL byte or a form feed. Also check for a missing XML declaration when the document starts with whitespace, and for duplicate attributes on the same element. - Correct the data at the source. If the XML is generated by your application, fix the serializer (most languages have an XML builder that escapes automatically; hand-concatenated strings are the usual culprit). If the XML is already stored in a text column, update the offending rows after validating each corrected value with xmllint.
- Re-run the original statement. Once the corrected value passes both xmllint and a direct
::xmlcast, run the original INSERT, UPDATE, or query again. If it still fails, the DETAIL line will point to a different position, which usually means a second problem further into the document. - Add a guard so it does not recur. Where the input is untrusted, validate before insert. You can wrap the cast in a check, or use
xml_is_well_formed(text)(andxml_is_well_formed_documentorxml_is_well_formed_content) in a CHECK constraint or application-side validation to reject bad XML with a clearer message than 2200N.
Common Mistakes
- Assuming a database setting can disable the check. There is no
xml_checkor similar parameter that turns off well-formedness validation. Thexmltype always validates on input. - Escaping only the first ampersand. Every literal
&in text content or attribute values must be written as&, not just the one the error pointed at. A second failure usually appears immediately after the first fix. - Treating HTML as XML. HTML allows unclosed tags like
<br>and<img>; XML does not. If you are storing HTML, either store it astextor convert it to XHTML first. - Ignoring encoding. A document declared as UTF-8 that actually contains Latin-1 bytes will fail. Check the byte sequence around the reported position with a hex viewer.
- Fixing the row but not the code. If the application keeps generating malformed XML, the next insert fails the same way. Fix the serializer, not just the data.
Tips
- Use
SELECT xml_is_well_formed(your_column) FROM your_table WHERE NOT xml_is_well_formed(your_column);to find every bad row in a text column at once before converting it toxml. - When building XML in SQL, prefer
xmlelement,xmlattributes, andxmlforestover string concatenation; they escape values correctly. - Keep a copy of the failing value before you fix it. It is the fastest way to confirm a fix and to write a regression test.
- If you regularly ingest third-party XML, validate against the schema with
xml_is_well_formed_documentand, where a schema exists, an external validator, before loading.
Troubleshooting
The error persists after fixing the reported position. The DETAIL line reports the first failure only. Re-run xmllint on the whole document; it will list every problem in one pass.
The literal cast works but the INSERT fails. Check for triggers, rules, or generated columns on the table that modify the value. Also check the client encoding: SHOW client_encoding; should match the encoding your application actually sends.
You cannot find the offending row in a large table. Narrow it down with SELECT ctid, left(your_column, 200) FROM your_table WHERE NOT xml_is_well_formed(your_column) LIMIT 20; and work through the results in batches.
The XML looks fine in a browser but fails in PostgreSQL. Browsers are lenient HTML parsers. Paste the value into xmllint or an XML validator, not a browser tab.
You need to load legacy data that will never be valid XML. Store it in a text column and cast to xml only when you are sure it is well-formed, or clean it during the load with a scripted pass through an XML parser.
Frequently Asked Questions
What does SQLSTATE 2200N mean exactly?
It is the class 22 (data exception) code for invalid XML content. PostgreSQL raises it when a value cannot be parsed as well-formed XML, either on cast to xml, on insert into an xml column, or inside XML-building functions.
Can I turn off XML validation in PostgreSQL?
No. The xml type validates input by design. The only alternative is to store the data as text and validate it yourself when needed.
Does 2200N mean the XML is invalid against a schema?
No. 2200N is about well-formedness only: tags balanced, entities escaped, characters legal. Schema validation is a separate step you perform with an external validator.
Why does my XML fail only sometimes?
Usually because user-supplied text occasionally contains an ampersand or angle bracket. Those inputs are fine as text but break XML unless escaped. Fix the escaping in the code that builds the document.
Which functions help me find bad XML before it errors?
xml_is_well_formed, xml_is_well_formed_document, and xml_is_well_formed_content return a boolean and never raise 2200N, so they are safe to use in WHERE clauses and CHECK constraints.