You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用pandas.to_xml()导出嵌套XML时转义字符问题排查

问题根源

当你用pandas.read_sql读取PostgreSQL的XML类型字段时,pandas默认会将其转换为Python字符串(str类型)存储在DataFrame中。而to_xml方法为了保证输出的XML格式合法,会对字符串中的特殊字符(包括<、>)进行XML实体转义,把<变成&lt;,>变成&gt;,这就导致原本的嵌套XML结构被破坏。

解决方案

要保留原始嵌套XML,核心是让to_xml识别出xml_part列的内容是合法的XML片段,不对其进行转义。以下是两种可行的实现方式:

方式一:自定义XML格式化函数

利用pandas.io.xml.XmlFormatter自定义指定列的格式化逻辑,直接返回原始XML字符串,跳过转义步骤:

import pandas as pd
from pandas.io.xml import XmlFormatter
from sqlalchemy import create_engine

# 连接数据库并读取数据
engine = create_engine("postgresql://your_user:your_pass@your_host/your_db")
df = pd.read_sql("SELECT id, xml_part FROM text_xml", engine)

# 定义针对xml_part列的格式化函数
def keep_raw_xml(x):
    return x

# 创建格式化器,指定xml_part列使用自定义函数
formatter = XmlFormatter(cols={"xml_part": keep_raw_xml})

# 输出XML,禁用索引并使用自定义格式化器
df.to_xml("output.xml", index=False, formatter=formatter)

方式二:读取时保留XML对象类型

通过SQLAlchemy的PostgreSQL XML类型,将数据库中的XML字段直接读取为etree.Element对象,这样to_xml会识别其为XML节点,自动保留嵌套结构:

import pandas as pd
from sqlalchemy import create_engine
from sqlalchemy.dialects.postgresql import XML

# 连接数据库
engine = create_engine("postgresql://your_user:your_pass@your_host/your_db")

# 读取时指定xml_part列的类型为PostgreSQL XML
df = pd.read_sql(
    "SELECT id, xml_part FROM text_xml",
    engine,
    dtype={"xml_part": XML}
)

# 直接输出XML,此时xml_part的嵌套结构会被保留
df.to_xml("output.xml", index=False)
注意事项
  • 方式一中要确保xml_part列的字符串内容是合法的XML片段,否则直接插入会导致整个输出XML格式错误。
  • 方式二依赖SQLAlchemy对PostgreSQL XML类型的支持,需要确保你的SQLAlchemy版本(建议1.3+)和psycopg2驱动是最新的。

内容的提问来源于stack exchange,提问作者Alexex93

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.10 04:07:23