在 postgresql 中使用 xml?

Work with xml in postgresql?

我有一份 xml 文件。将其放入 posgresql table。 我是这样说的。

create or replace function bytea_import(p_path text, p_result out bytea) 
                   language plpgsql as $$
declare
  l_oid oid;
  r record;
begin
  p_result := '';
  select lo_import(p_path) into l_oid;
  for r in ( select data 
             from pg_largeobject 
             where loid = l_oid 
             order by pageno ) loop
    p_result = p_result || r.data;
  end loop;
  perform lo_unlink(l_oid);
end;$$;


 insert into mydocs(docform,content)
 values (3, convert_from(bytea_import('D:/html/ex08.xml'), 'utf-8'));

我需要更改文档。例如

<?xml version="1.0"?>
<list_of_items>
<item id="1"><first/>first</item>
<item id="2">second <sub_item>subsecond 1</sub_item></item>
<item id="3">third</item>
<item id="4"><last/>last</item>
</list_of_items>

必须从这个文档中取出文本并放入其他table:

first 放入 table 的第 1 列 2

second 放入 table 的第 2 列 2

subsecond 放入 table 的第 3 列 2

third 放入 table 的第 4 列 2

last放入table2

的第5列

Gab 回答得很好,但我还有 1 个问题。 如何为任何一种 xml 制作它。 如何删除像

这样的行
<?xml version="1.0"?>
<list_of_items>
</list_of_items>

并选择任意文本,不进行 xpath 搜索?

您赢得了当天最难的问题。为它点赞!

使用以下查询:

WITH x(col) AS (
    SELECT '<?xml version="1.0"?>
    <list_of_items>
    <item id="1"><first/>first</item>
    <item id="2">second <sub_item>subsecond 1</sub_item></item>
    <item id="3">third</item>
    <item id="4"><last/>last</item>
    </list_of_items>
    '::xml
), interpreted as (
    SELECT xpath('.//item/text()', col) AS val,
           xpath('.//sub_item/text()', col) AS val2
    FROM   x
)
SELECT val[1] as col1, val[2] as col2, val2[1] as col3, val[3] as col4, val[4] as col5
FROM interpreted
;

您可以获得:

 col1  |  col2   |    col3     | col4  | col5 
-------+---------+-------------+-------+------
 first | second  | subsecond 1 | third | last
(1 row)