Import XML files to PostgreSQL

后端 未结 4 1541
隐瞒了意图╮
隐瞒了意图╮ 2020-12-01 04:33

I do have a lot of XML files I would like to import in the table xml_data:

create table xml_data(result xml);

To do this I hav

4条回答
  •  一生所求
    2020-12-01 05:36

    I would try a different approach: read the XML file directly into variable inside a plpgsql function and proceed from there. Should be a lot faster and a lot more robust.

    CREATE OR REPLACE FUNCTION f_sync_from_xml()
      RETURNS boolean AS
    $BODY$
    DECLARE
        myxml    xml;
        datafile text := 'path/to/my_file.xml';
    BEGIN
       myxml := pg_read_file(datafile, 0, 100000000);  -- arbitrary 100 MB max.
    
       CREATE TEMP TABLE tmp AS
       SELECT (xpath('//some_id/text()', x))[1]::text AS id
       FROM   unnest(xpath('/xml/path/to/datum', myxml)) x;
       ...
    

    You need superuser privileges, and file must be local to the DB server, in an accessible directory.
    Complete code example with more explanation and links:

    • XML data to PostgreSQL database

提交回复
热议问题