PostgreSQL Error 22001 Not an XML Document Fix
In this article
PostgreSQL error 22001 (specifically the "not an XML document" message) occurs when you attempt to insert, update, or cast a string into an XML data type, but the string does not conform to the required XML syntax rules. To fix this, you must ensure the string begins with a valid root element, contains properly closed tags, and uses valid character encoding before passing it to the XML parser.
What You'll Need
- Access to a PostgreSQL database instance via psql, pgAdmin, or a similar IDE.
- The specific SQL query or application code that is triggering the error.
- The raw data string that is being passed into the XML column or function.
- Basic knowledge of XML structure (tags, attributes, and nesting).
Step-by-Step
- Isolate the Offending Data
The first step is to identify exactly which row or string is causing the failure. If you are running a bulk insert or an update on a large table, the error will stop the entire transaction. Run a SELECT query on the source data to find strings that are empty, null, or contain non-XML characters. If the data is coming from an external API or a CSV file, inspect the raw source to see if any records are truncated or missing closing tags. - Verify the Root Element
A common cause of error 22001 is a "fragment" that lacks a single root element. PostgreSQL requires a well-formed XML document, meaning everything must be wrapped in one parent tag. For example,<name>John</name><age>30</age>will fail because there are two root elements. To fix this, wrap the content in a parent tag:<user><name>John</name><age>30</age></user>. - Check for Special Character Escaping
XML has strict rules about reserved characters. If your data contains characters like&(ampersand),<(less than), or>(greater than) inside the text content, the parser will think it is the start of a new tag and throw error 22001. You must replace these with their corresponding entities:- Replace
&with& - Replace
<with< - Replace
>with> - Replace
"with" - Replace
'with'
- Replace
- Validate the XML Prolog
If your data includes an XML declaration (the line starting with<?xml version="1.0"...>), ensure it is the absolute first thing in the string. If there is a leading space, a newline, or a hidden byte-order mark (BOM) before the<?xmltag, PostgreSQL may fail to recognize it as a valid document. Trim all leading whitespace from your input strings before casting to XML. - Test with Explicit Casting
Before running your full update, test a single suspect string using an explicit cast in a query window. Use the syntaxSELECT 'your_xml_string'::xml;. If this returns the same 22001 error, the string is fundamentally malformed. If it succeeds, the issue may be related to how your application is passing the variable (e.g., encoding issues or null handling). - Implement a Validation Layer
To prevent this error from crashing your production environment, implement a check in your application logic or a database trigger. Use a regular expression or a lightweight XML validator in your backend language (like Python's ElementTree or Java's DOM parser) to verify the string is well-formed before sending theINSERTorUPDATEcommand to PostgreSQL.
Common Mistakes
One of the most frequent mistakes is treating the XML type as a simple text field. Developers often concatenate strings to build XML, which leads to missing closing tags or mismatched case (e.g., opening with <Data> and closing with </data>). XML is case-sensitive; these tags are not the same, and the parser will reject the document.
Another mistake is attempting to cast an empty string '' to XML. An empty string is not a valid XML document. If your data can be empty, you should use NULL instead of an empty string. Casting NULL::xml is perfectly valid, whereas casting ''::xml will trigger the 22001 error.
Finally, users often forget about character encoding. If the XML document specifies encoding="UTF-8" but the actual byte stream is encoded in Latin-1 or UTF-16, the PostgreSQL parser may encounter a character it cannot process, resulting in a failure to recognize the document as valid XML.
Tips
When dealing with highly unpredictable data, consider storing the information in a TEXT or JSONB column first. Once the data is safely inside the database, you can use a staging table to clean the strings—removing illegal characters and adding root elements—before finally casting the cleaned data into a formal XML column.
Use the xmlelement() and xmlforest() functions provided by PostgreSQL to generate XML dynamically. These functions automatically handle the escaping of special characters and ensure that the resulting XML is well-formed, completely eliminating the risk of error 22001 during the generation process.
If you are importing large datasets via the COPY command, use a temporary table with TEXT columns. This allows you to load the data without the strict XML validation. You can then run a query to identify which rows fail the ::xml cast using a CASE statement or a custom function, allowing you to fix only the broken records rather than failing the entire import.
Troubleshooting
If you have checked the root elements and special characters but still receive the error, try the following steps in order:
First, check for hidden characters. Use a hex editor or a function like encode(column_name::bytea, 'hex') to see if there are non-printable characters or null bytes (\000) embedded in the string. These are invisible in most SQL editors but will break the XML parser.
Second, verify the PostgreSQL version. While the XML standard is consistent, older versions of PostgreSQL may have different behaviors regarding certain XML entities. Ensure your database is updated to a supported version.
Third, test the string in an external XML validator (like an online XSD validator). If an external tool also flags the document as "not well-formed," the issue is with the data source, not the database. The external tool will usually give you a specific line and column number where the error occurs, which is much more helpful than the generic PostgreSQL 22001 message.
Fourth, if the error occurs during a CAST from a TEXT column to an XML column in a view or a query, try using trim(both ' ' from column_name)::xml to ensure no stray whitespace is confusing the parser.
Frequently Asked Questions
Is an empty string considered a valid XML document?
No. An empty string is not a valid XML document because it lacks a root element. To avoid error 22001, use a NULL value or a minimal valid tag like <empty/>.
What is the difference between a well-formed XML and a valid XML?
A well-formed XML document follows the basic syntax rules (closed tags, root element, proper escaping). A valid XML document is well-formed AND conforms to a specific schema (DTD or XSD). PostgreSQL error 22001 refers to "well-formedness"; it means the basic syntax is broken.
Can I use JSONB instead of XML to avoid this error?
Yes. If you have control over the data format, JSONB is often more flexible and has better performance in PostgreSQL. However, if you are required to use XML for interoperability, you must stick to the XML type and ensure strict formatting.
Why does my XML work in a browser but fail in PostgreSQL?
Web browsers are designed to be "forgiving." They often automatically fix missing closing tags or ignore stray characters to display the page. PostgreSQL's XML parser is strict and follows the W3C standard exactly; it will not guess what you meant and will throw an error instead.
How do I find which specific row in a million-row table is causing the error?
You can create a custom PL/pgSQL function that attempts to cast a string to XML within a BEGIN...EXCEPTION block. The function should return TRUE if the cast succeeds and FALSE if it fails. You can then run this function across your table to filter for all rows where the result is FALSE.