0

I need to be able to export/import XML data from/to a PostgresQL database. I've reviewed the documentation, and determined that I can readily export XML using a query or a table. What would be the simplest way to re-import the same XML into the same database? I prefer not using a third-party tool, but will handle any programming in PG functions and Java/JDBC.

I will vote on anyone providing a useful information.

MAbraham1
  • 1,717
  • 4
  • 28
  • 45
  • 2
    Just convert the XML into the corresponding insert/update queries. No? – Jeremy May 21 '12 at 18:55
  • 1
    From [PostgreSQL mailing lists](http://www.postgresql.org/community/lists/): [Re: Import data from XML file](http://archives.postgresql.org/pgsql-general/2009-08/msg01089.php) – user272735 May 21 '12 at 19:23
  • 1
    This [closely related answer](http://stackoverflow.com/a/7628453/939860) to a related question should help. – Erwin Brandstetter May 21 '12 at 20:37
  • Erwin, thank you for the that. I wouldn't have posted the question had I seen that. It is frustrating for a new StackO user to be docked rep pts without explanation. – MAbraham1 May 21 '12 at 20:53

1 Answers1

4

Create a "staging" table that contains one row for each XML that you want to import.

Then use the XML functions (e.g. xpath_table) to slice that XML column into rows and columns. Something like this:

-- make sure xpath_table is available
create extension xml2;

-- create XML staging table
create table xml_test (id integer, xml text);

-- create sample XML document
insert into xml_test  (id, data)
values
(1, '<person-list>
    <person>
        <id>42</id>
        <firstname>Arthur</firstname>
        <lastname>Dent</lastname>
    </person>
    <person>
        <id>43</id>
        <firstname>Zaphod</firstname>
        <lastname>Beeblebrox</lastname>
    </person>
</person-list>'
);

Now if your target table is e.g.:

create table person 
(
   id integer not null primary key,
   firstname text,
   lastname text
);

you can use:

insert into person (id, firstname, lastname)
select person_id, firstname, lastname
from xpath_table('id', 'xml', 'xml_test', 
                 '/person-list/person/id|/person-list/person/firstname|/person-list/person/lastname', 'id=1')
as t (docid integer, person_id integer, firstname text, lastname text)

The last parameter to the function id=1 is the row that is selected from the table containing the XML column. If you have more than one document in there, you need to pick the one that matches the xpath expressions

You can also create a similar view without the xml2 module, using the core XML functions. See the link user272735 has posted in the comments.