在 postgresql 中导入 xml 数据

Import xml data in postgresql

我尝试从 XML 插入到 postgresql table 数据 这是示例 XML:

<?xml version="1.0" encoding="UTF-8"?>
<ActualStatuses>
   <ActualStatus ACTSTATID="0" NAME="Not actual" />
   <ActualStatus ACTSTATID="1" NAME="Актуальный" />
</ActualStatuses>

要加载 XMl 我使用这个函数:

CREATE OR REPLACE FUNCTION bytea_import(IN p_path text, OUT p_result bytea)
  RETURNS bytea AS
$BODY$
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;$BODY$
  LANGUAGE plpgsql VOLATILE
  COST 100;
ALTER FUNCTION bytea_import(text)
  OWNER TO postgres;

对于从 XML 到 postgresql table 的插入值,我使用精简查询:

INSERT INTO actualstatuses(
    SELECT
        (xpath('//ActualStatus/@ACTSTATID', myTempTable))[1]::text::bigint AS ACTSTATID,
        (xpath('//ActualStatus/@NAME', myTempTable))[1]::text AS NAME
    FROM
        unnest(xpath('//ActualStatus', convert_from(public.bytea_import('C:/fias/update/AS_ACTSTAT.XML'), 'utf8')::xml)) AS myTempTable);

并且有解析器错误:

invalid XML content
SQL-status: 2200N
Entity: line 1: parser error : XML declaration allowed only at the start of the document
<?xml version="1.0" encoding="utf-8"?><AddressObjectTypes><AddressObjectType 

但是,如果我在 XML 中删除 <?xml version="1.0" encoding="utf-8"?>,这个效果很好。我有大约 20 XML 个文件,其中一些非常大。如何摆脱这个错误?

   INSERT INTO actualstatuses(
    SELECT
        (xpath('//ActualStatus/@ACTSTATID', myTempTable))[1]::text::bigint AS ACTSTATID,
        (xpath('//ActualStatus/@NAME', myTempTable))[1]::text AS NAME
    FROM
        unnest(xpath('//ActualStatus', replace(convert_from(bytea_import('C:/fias/update/AS_ACTSTAT.XML'), 'utf8'),'<?xml version="1.0" encoding="utf-8"?>','')::xml)) AS myTempTable);