【问题标题】:XPath query into hierarchical data, preserving ancestor–descendant relationshipXPath 查询分层数据,保留祖先-后代关系
【发布时间】:2011-11-22 00:02:25
【问题描述】:

我如何向 PostgreSQL 表达我想要在 XPath 查询中同时来自多个层级的值

我有一个具有多级层次结构的文档(在 PostgreSQL XML 值中)。对于这个问题,可以创建一个示例:

SELECT XMLPARSE(DOCUMENT '
    <parrots>
        <parrot name="Fred">
            <descriptor>Beautiful plumage</descriptor>
            <descriptor>Resting</descriptor>
        </parrot>
        <parrot name="Ethel">
            <descriptor>Pining for the fjords</descriptor>
            <descriptor>Stunned</descriptor>
        </parrot>
    </parrots>
    ') AS document
INTO TEMPORARY TABLE parrot_xml;

我可以从该文档中获得不同级别的信息。

=> SELECT
        (XPATH('./@name', parrot.node))[1] AS name
    FROM (             
        SELECT
            UNNEST(XPATH('./parrot', parrot_xml.document))
                AS node
        FROM parrot_xml
        ) AS parrot
    ;
 name  
-------
 Fred
 Ethel
(2 rows)

=> SELECT
        (XPATH('./text()', descriptor.node))[1] AS descriptor
    FROM (
        SELECT
            UNNEST(XPATH('./parrot/descriptor', parrot_xml.document))
                AS node
        FROM parrot_xml
        ) AS descriptor
    ;
      descriptor       
-----------------------
 Beautiful plumage
 Resting
 Pining for the fjords
 Stunned
(4 rows)

不过,我想不通的是如何连接多个级别,以便查询返回与其应用的鹦鹉相关的每个描述符。

=> SELECT
        ??? AS name,
        ??? AS descriptor
    FROM
        ???
    ;
 name         descriptor       
------- -----------------------
 Fred    Beautiful plumage     
 Fred    Resting               
 Ethel   Pining for the fjords 
 Ethel   Stunned               
(4 rows)

如何做到这一点?应该用什么来代替“???”?

单个复杂的 XPath 查询——但是如何同时引用多个级别?几个 XPath 查询——但是如何为结果关系保留祖先-后代信息?还有什么?

【问题讨论】:

    标签: xml postgresql xpath


    【解决方案1】:

    试试这个:

    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;
    

    准确地产生请求的输出。

    首先,在子查询中,我检索整个鹦鹉节点。每行一个节点。

    接下来,我使用 xpath() 获取名称和描述符。两者都是数组。我取name 的第一个(也是唯一一个)元素,并用`unnest() 拆分descriptor 数组,从而得到所需的结果。

    我最近写了一个comprehensive answer to a related question。您可能会感兴趣。

    【讨论】:

    • 非常好,但它也显示了使用 PostgreSQL 处理 XML 的局限性。嗯。带有&lt;xsl:output method="pgtable"/&gt; 选项的xslt_process() 将是完美的:-)。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-04-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多