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

PostgreSQL使用PLPython实现JSON转带命名空间XML的问题及方案

JSON转XML保留命名空间根节点解决方案

问题原因

你当前使用的json2xml库默认会将JSON顶层的唯一键作为<key>标签的name属性处理,不会直接将该键名作为根节点标签名,因此会出现根节点不符合预期的问题。

推荐解决方案:使用xmltodict实现

该方案逻辑更简洁,对命名空间的兼容性更好,不需要依赖json2xml的转换规则即可直接输出符合要求的结果:

import xmltodict
import json
import plpy # 仅PostgreSQL存储过程环境需要保留,其他环境可删除

# 读取JSON源数据
sample_json = plpy.execute("select content from items")
# 将JSON字符串加载为字典
data = json.loads(sample_json[0]["content"])
# 转换为XML:pretty=True自动生成缩进匹配格式要求,full_document=False可去掉开头的XML声明
xml_result = xmltodict.unparse(data, pretty=True, full_document=False)

return str(xml_result)

备选方案:继续使用json2xml库的调整方法

如果已有逻辑基于json2xml不想大幅改动,可以通过指定参数的方式修正根节点输出:

from json2xml import json2xml
from json2xml.utils import readfromstring

json_str = '{"ra:covered-product-agreement":{"login":"mojombo","id":1,"avatar_url":"https://avatars0.githubusercontent.com/u/1?v=4"}}'
data = readfromstring(json_str)
# 指定custom_root为带命名空间的根节点名,同时设置wrapper=None移除默认的外层包裹标签
return json2xml.Json2xml(data, attr_type=False, custom_root="ra:covered-product-agreement", wrapper=None).to_xml()
  • 推荐优先使用xmltodict方案,适配性更强,后续如果有其他命名空间的需求也不需要额外调整参数
  • json2xml方案需要每次手动指定根节点名,适合固定根节点的场景

内容的提问来源于stack exchange,提问作者althaf a s

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 07:15:06