Postgres + Xml Part 1

Posted by Kerry Tue, 22 Aug 2006 17:18:00 GMT

Well, it’s tomorrow(plus a few days) so here is a quick intro to using the xml features in Postgres.

First, we need a table, and some data:

create table xml_test (
    id int not null,
    xml text not null
);

insert into xml_test(id, xml) values (1, 
    '<root>
       <child att="a" >child a</child>
       <child att="b" >child b</child>
     </root>');
insert into xml_test(id, xml) values (2, 
     '<root>
        <child att="c" >child c</child>
        <child att="d">child d</child>
      </root>');

To find all the functions you can use:

\df

A couple of useful functions are xpath_bool, which returns true when an xpath query has a result; and xpath_nodeset, which returns a nodeset(go figure) from an xpath.

Lets see how xpath_bool works:

select id 
  from xml_test 
  where xpath_bool(xml, '/root/child[@att="a"]');
 id
 ----
  1
 (1 row)

select id 
  from xml_test 
  where xpath_bool(xml, '/root/child[@att="c"]');
 id
 ----
  2
 (1 row)

and xpath_nodeset doesn’t hold many surprises:

select xpath_nodeset(xml, '//root/child') 
  from xml_test;
 xpath_nodeset
 --------------------------------------------------------------
  <child att="a">child a</child>
    <child att="b">child b</child>
  <child att="c">child c</child>
    <child att="d">child d</child>
 (2 rows)

putting these together:

select xpath_nodeset(xml, '//root/child') 
  from xml_test 
  where
    xpath_bool(xml, '/root/child[@att="a"]');
 xpath_nodeset
 --------------------------------------------------------------
  <child att="a">child a</child><child att="b">child b</child>
 (1 row)

Pretty straight forward stuff.

Note: Excuse the crazy formatting, the default typo theme is whack.

Comments

Leave a response

Comments