XML shredding in postgresql

In SQL Server 2005 T-SQL, I can reduce the XML value as follows:

SELECT
    t.c.value('./ID[1]', 'INT'),
    t.c.value('./Name[1]', 'VARCHAR(50)')
FROM @Xml.nodes('/Customer') AS t(c)

where @Xml is an xml value similar to

'<Customer><ID>23</ID><Name>Google</Name></Customer>'

Can someone help me achieve the same result in PostgreSQL (possibly in PL / pgSQL)?

+5
source share
2 answers

The function xpathwill return an array of nodes so that you can extract multiple partners. Usually you do something like:

SELECT (xpath('/Customer/ID/text()', node))[1]::text::int AS id,
  (xpath('/Customer/Name/text()', node))[1]::text AS name,
  (xpath('/Customer/Partners/ID/text()', node))::_text AS partners
FROM unnest(xpath('/Customers/Customer',
'<Customers><Customer><ID>23</ID><Name>Google</Name>
 <Partners><ID>120</ID><ID>243</ID><ID>245</ID></Partners>
</Customer>
<Customer><ID>24</ID><Name>HP</Name><Partners><ID>44</ID></Partners></Customer>
<Customer><ID>25</ID><Name>IBM</Name></Customer></Customers>'::xml
)) node

unnest(xpath(...)), xml ; xpath(), . XML, text, int ( date, numeric ..) . , , . XML Postgres

+10

xpath- PostgreSQL XML.

: :

SELECT
    xpath('/Customer/ID[1]/text()', content),
    xpath('/Customer/Name[1]/text()', content),
    *
FROM
    (SELECT '<Customer><ID>23</ID><Name>Google</Name></Customer>'::xml AS content) AS sub;
+5

All Articles