问题描述
虽然我使用 @abelisto 在此 thread 上提供的解决方案将 XML 字段转换为 JSON,但我遇到以下问题:
- 在我的本地机器上使用这个版本可以完美运行 [Postgresql 12.5 (Ubuntu 12.5-0ubuntu0.20.04.1) on x86_64-pc-linux-gnu,由 gcc (Ubuntu 9.3.0-17ubuntu1~20.04) 9.3 编译。 0,64 位]
- 将相同的函数复制到我的生产服务器 [Postgresql 9.5.3 on x86_64-pc-linux-gnu,由 gcc (Ubuntu 4.8.2-19ubuntu1) 4.8.2,64-bit 编译] 我收到错误 sql 错误[42883]:错误:函数 xml_to_json(xml) 不存在,但该函数已存在于 pg_catalog 中,具有足够的数据类型并且与我的本地相同。
我没有找到是兼容性问题还是 postgres 文档中的内容。有什么建议吗?
提前致谢
代码如下:
create or replace function prod.xml_to_json(p_xml xml) returns jsonb as $$
declare
result json;
root text;
childs jsonb;
attr jsonb;
txt text;
begin
-- Get root element name
select (xpath('name(/*)',p_xml))[1]::text into root;
-- Process child nodes
select json_agg(xml_to_json(z))
from unnest(xpath('/'||root||'/*',p_xml)) with ordinality as c(z,i)
into childs;
-- Read attributes
select jsonb_agg(jsonb_build_object((xpath('name(/'||root||'/@*['||i||'])',p_xml))[1]::text,v))
from unnest(xpath('/'||root||'/@*',p_xml)::text[]) with ordinality as a(v,i)
into attr;
-- Read text
select (xpath('/'||root||'/text()',p_xml))[1]::text into txt;
-- Build object
result := jsonb_build_object(root,jsonb_build_object('attr',attr,'text',txt,'childs',childs));
return result;
end $$ language plpgsql immutable;
测试数据:
with t(x) as (values
('<root bar="foo" name="test" foo="bar">
<aaa bbb="111">
foo
bar
</aaa>
<bbb>
<ccc>222</ccc>
</bbb>
</root>'::xml),('<?xml version="1.0" encoding="UTF-8"?>
<bookstore>
<book>
<title lang="en">Harry Potter</title>
<price>29.99</price>
</book>
<book>
<title lang="en">Learning XML</title>
<price>39.95</price>
</book>
</bookstore>'))
select prod.xml_to_json(x) from t;
结果
sql Error [42883]: ERROR: function xml_to_json(xml) does not exist
Hint: No function matches the given name and argument types. You might need to add explicit type casts.
Where: PL/pgsql function prod.xml_to_json(xml) line 12 at sql statement
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)