PostgreSQL11 xpath 查询无法正常工作
PostgreSQL11 xpath query not working properly
当我在 Postgres 10.12 中执行以下查询时,它工作正常。
SELECT (xpath('./sid/text()', c.node))[1]::text::bigint AS STUDENT_ID,
(xpath('./name/text()', c.node))[1]::text AS STUDENT_NAME
from (
select unnest(xpath('/data', '<data><sid>112233</sid><name>John</name></data>'::xml)) AS node
) c;
输出:
但是当我在 Postgres 11.7 中执行相同的查询时,它不起作用。
解决此问题的解决方案是什么?
这是由change造成的:
Correctly handle relative path expressions in xmltable(), xpath(), and other XML-handling functions (Markus Winand)
Per the SQL standard, relative paths start from the document node of the XML input document, not the root node as these functions previously did.
因此您需要将其更改为:
SELECT (xpath('/data/sid/text()', c.node))[1]::text::bigint AS STUDENT_ID,
(xpath('/data/name/text()', c.node))[1]::text AS STUDENT_NAME
from (
select unnest(xpath('/data', '<data><sid>112233</sid><name>John</name></data>'::xml)) AS node
) c;
因为内部 xpath
也会 return <data>
标签:
select unnest(xpath('/data', '<data><sid>112233</sid><name>John</name></data>'::xml)) AS node
结果:
<data>
<sid>112233</sid>
<name>John</name>
</data>
但是,我会为此使用 xmltable:
select *
from xmltable('/data'
passing xml('<data><sid>112233</sid><name>John</name></data>')
columns
student_id bigint path 'sid',
student_name text path 'name')
当我在 Postgres 10.12 中执行以下查询时,它工作正常。
SELECT (xpath('./sid/text()', c.node))[1]::text::bigint AS STUDENT_ID,
(xpath('./name/text()', c.node))[1]::text AS STUDENT_NAME
from (
select unnest(xpath('/data', '<data><sid>112233</sid><name>John</name></data>'::xml)) AS node
) c;
输出:
但是当我在 Postgres 11.7 中执行相同的查询时,它不起作用。
解决此问题的解决方案是什么?
这是由change造成的:
Correctly handle relative path expressions in xmltable(), xpath(), and other XML-handling functions (Markus Winand)
Per the SQL standard, relative paths start from the document node of the XML input document, not the root node as these functions previously did.
因此您需要将其更改为:
SELECT (xpath('/data/sid/text()', c.node))[1]::text::bigint AS STUDENT_ID,
(xpath('/data/name/text()', c.node))[1]::text AS STUDENT_NAME
from (
select unnest(xpath('/data', '<data><sid>112233</sid><name>John</name></data>'::xml)) AS node
) c;
因为内部 xpath
也会 return <data>
标签:
select unnest(xpath('/data', '<data><sid>112233</sid><name>John</name></data>'::xml)) AS node
结果:
<data>
<sid>112233</sid>
<name>John</name>
</data>
但是,我会为此使用 xmltable:
select *
from xmltable('/data'
passing xml('<data><sid>112233</sid><name>John</name></data>')
columns
student_id bigint path 'sid',
student_name text path 'name')