惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
T
Tailwind CSS Blog
J
Java Code Geeks
Microsoft Azure Blog
Microsoft Azure Blog
GbyAI
GbyAI
爱范儿
爱范儿
量子位
Martin Fowler
Martin Fowler
V
V2EX
博客园 - 三生石上(FineUI控件)
I
InfoQ
MongoDB | Blog
MongoDB | Blog
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
N
Netflix TechBlog - Medium
D
DataBreaches.Net
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
Last Week in AI
Last Week in AI
U
Unit 42
Apple Machine Learning Research
Apple Machine Learning Research
H
Help Net Security
T
The Blog of Author Tim Ferriss
Hugging Face - Blog
Hugging Face - Blog
美团技术团队
Engineering at Meta
Engineering at Meta

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant
PostgreSQL 2200M Error: Causes and Solutions Complete Guide
umzzil nng · 2026-06-15 · via DEV Community

umzzil nng

PostgreSQL Error 2200M: invalid xml document

PostgreSQL error 2200M: invalid xml document is raised when an XML value passed to XMLPARSE(DOCUMENT ...) or inserted into an xml-typed column does not conform to the W3C XML specification for a well-formed document. Unlike 2200N: invalid xml content, this error specifically targets document-level structural violations, such as missing or multiple root elements. It commonly appears during data migrations, API integrations, or when dynamically building XML strings in application code.


Top 3 Causes & SQL Examples

1. Multiple or Missing Root Elements

An XML document must have exactly one root element. Passing fragments or multiple top-level elements will immediately trigger this error.

-- Bad: multiple root elements
SELECT XMLPARSE(DOCUMENT '<item>A</item><item>B</item>');
-- ERROR:  invalid xml document

-- Bad: no root element at all
SELECT XMLPARSE(DOCUMENT 'just some text');
-- ERROR:  invalid xml document

-- Good: wrap everything in a single root
SELECT XMLPARSE(DOCUMENT '<root><item>A</item><item>B</item></root>');

2. Unescaped Special Characters or Unclosed Tags

Characters like &, <, and > must be escaped as XML entities. Unclosed tags are also a common culprit when XML is built by string concatenation.

-- Bad: unescaped ampersand
SELECT XMLPARSE(DOCUMENT '<root><price>10 & 20</price></root>');
-- ERROR:  invalid xml document

-- Bad: unclosed tag
SELECT XMLPARSE(DOCUMENT '<root><item>value</root>');
-- ERROR:  invalid xml document

-- Good: use PostgreSQL built-in XML functions (auto-escaping)
SELECT XMLELEMENT(NAME "root",
    XMLELEMENT(NAME "price", '10 & 20')
);

-- Good: manually escape entities
SELECT XMLPARSE(DOCUMENT '<root><price>10 &amp; 20</price></root>');

3. Encoding Declaration Mismatch

An <?xml version="1.0" encoding="..."> declaration that does not match the actual database encoding will cause parsing to fail.

-- Check your database encoding first
SHOW server_encoding;
-- e.g., UTF8

-- Bad: declared encoding differs from DB encoding
SELECT XMLPARSE(DOCUMENT
    '<?xml version="1.0" encoding="EUC-KR"?><root>data</root>'
);
-- May raise: invalid xml document

-- Good: match the declaration to your DB encoding
SELECT XMLPARSE(DOCUMENT
    '<?xml version="1.0" encoding="UTF-8"?><root>data</root>'
);

-- Good: omit the declaration entirely
SELECT XMLPARSE(DOCUMENT '<root>data</root>');

-- Utility function to strip problematic XML declarations
CREATE OR REPLACE FUNCTION strip_xml_declaration(p_xml TEXT)
RETURNS TEXT AS $$
BEGIN
    RETURN regexp_replace(p_xml, '^\s*<\?xml[^?]*\?>\s*', '', 'i');
END;
$$ LANGUAGE plpgsql;


Quick Fix Solutions

Use this validation helper before inserting any XML data:

-- Safe validation wrapper
CREATE OR REPLACE FUNCTION is_valid_xml(p_text TEXT)
RETURNS BOOLEAN AS $$
BEGIN
    PERFORM XMLPARSE(DOCUMENT p_text);
    RETURN TRUE;
EXCEPTION
    WHEN invalid_xml_document THEN RETURN FALSE;
    WHEN invalid_xml_content  THEN RETURN FALSE;
END;
$$ LANGUAGE plpgsql;

-- Filter out bad rows before bulk insert
INSERT INTO xml_store (payload)
SELECT XMLPARSE(DOCUMENT raw_xml)
FROM staging_table
WHERE is_valid_xml(raw_xml);


Prevention Tips

  1. Always use PostgreSQL's native XML builder functions (XMLELEMENT, XMLFOREST, XMLAGG) instead of string concatenation. These functions handle escaping and structure automatically, eliminating the most common sources of malformed documents.

  2. Add a CHECK constraint on XML columns and validate incoming data at the pipeline boundary before it reaches the database.

-- Add constraint using the validation function
ALTER TABLE xml_store
ADD CONSTRAINT chk_valid_xml_doc
CHECK (is_valid_xml(payload::text));

-- Prefer the native xml type over text for automatic parse-time validation
CREATE TABLE documents (
    id      SERIAL PRIMARY KEY,
    content XML NOT NULL  -- PostgreSQL validates on insert automatically
);


Related Errors

Code Name Notes
2200N invalid xml content Triggered by XMLPARSE(CONTENT ...) with structural issues
22000 data exception Parent category for all data-related exceptions
42804 datatype mismatch Occurs when a non-XML value is cast to the xml type incorrectly

📖 Want a more detailed guide?
Check out the full in-depth version (Korean) on oraerror.com — includes detailed analysis, additional SQL examples, and prevention tips.