PostgreSQL
 SQL >> Database >  >> RDS >> PostgreSQL

Estrarre XML gerarchico con XPath preservando le relazioni

Puoi usare xpath() e unnest() per estrarre nodi e attributi mantenendo le relazioni:

SELECT
  (xpath('./@name', parrot.node))[1] AS name,
  unnest(xpath('./descriptor/text()', parrot.node)) AS descriptor
FROM (
  SELECT unnest(xpath('./parrot', parrot_xml.document)) AS node
  FROM parrot_xml
) parrot;

La sottoquery estrae prima i nodi parrot, uno per riga. Poi xpath() recupera nome e descrittori come array. Il nome viene preso con indice 1, mentre i descrittori vengono espansi con unnest().