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.

4
  • 2
    Just convert the XML into the corresponding insert/update queries. No? Commented May 21, 2012 at 18:55
  • 1
    From PostgreSQL mailing lists: Re: Import data from XML file Commented May 21, 2012 at 19:23
  • 1
    This closely related answer to a related question should help. Commented May 21, 2012 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. Commented May 21, 2012 at 20:53

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.