Import xml data in postgresql

3k Views Asked by At

i try insert to postgresql table data from XML This is sample XML:

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

To load XMl i use this function:

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;

For insert value from XML to postgresql table i use thin query:

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

And have parser error:

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 

But if i remove <?xml version="1.0" encoding="utf-8"?> in XML this work great. I have about 20 XML files, some of is very large. How to get rid of this error?

1

There are 1 best solutions below

0
On BEST ANSWER
   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);