2016-12-28 90 views
0

我嘗試從XML 此插入到PostgreSQL表數據是示例XML:導入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我用薄查詢表:

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文件,其中一些非常大。如何擺脫這個錯誤?

+0

對我的作品)。請發佈更多細節:特別是你如何導入多個文件。 –

+0

@RadekPostołowicz以及我創建所有文件的SQL查詢,但我認爲它可以通過еру循環實現 –

回答

0
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);