XPath query into hierarchical data, preserving ancestor–descendant relationship

前端 未结 1 812
太阳男子
太阳男子 2021-01-22 11:09

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

相关标签:
1条回答
  • 2021-01-22 11:41

    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.

    0 讨论(0)
提交回复
热议问题