How can I express to PostgreSQL that I want values simultaneously from several hierarchical levels in an XPath query?
I have a document (in a PostgreSQL
Try this:
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;
Produces exactly the requested output.
First, in the subquery, I retrieve whole parrot-nodes. One node per row.
Next, I get the name and the descriptors with xpath(). Both are arrays. I take the first (and only) element of name
and split the descriptor
array with `unnest(), thereby arriving at the desired result.
I wrote a comprehensive answer to a related question recently. May be of interest to you.