Sql 在postgres中读取XML属性

Sql 在postgres中读取XML属性,sql,xml,postgresql,postgresql-9.6,Sql,Xml,Postgresql,Postgresql 9.6,我在Postgres中首次使用XML,并面临一个问题。 我在一个名为XMLCONTENT的变量中包含以下xml <?xml version="1.0" encoding="UTF-8"?> <Actions> <Action ActionID="90e0dbef-c23a-4fcd-bfa8-75d8bfa2c9e2" /> <Action ActionID="6a1998e1-70f1-4611-992a-7a27e2834c35" /&g

我在Postgres中首次使用XML,并面临一个问题。 我在一个名为XMLCONTENT的变量中包含以下xml

<?xml version="1.0" encoding="UTF-8"?>
<Actions>
   <Action ActionID="90e0dbef-c23a-4fcd-bfa8-75d8bfa2c9e2" />
   <Action ActionID="6a1998e1-70f1-4611-992a-7a27e2834c35" />
   <Action ActionID="43dd9a91-c6d3-4980-b211-9b3780f04305" />
   <Action ActionID="cdf01821-ac28-45a9-abf8-a7d7c9426518" />
   <Action ActionID="e86fac8a-84e3-41ba-8bee-c7ffd1ac8ee5" />
   <Action ActionID="a68dd878-ba1e-4fd9-b436-cdc15eccffb6" />
   <Action ActionID="cd863a5a-83e9-489e-b24d-ff6638c5b190" />
   <Action ActionID="720ba9c7-b797-4b2e-913e-11ac3ecd7b7f" />
   <Action ActionID="b6b35d0d-938e-45d3-96d1-0c8ca3ad59f3" MessageID="42f40c3a-4426-4506-86c5-222fb03c2114" />
</Actions>
但我得到了如下所示的错误输出


MessageID与错误的actionID链接。遍历此XML的正确方法是什么?

查询不起作用的原因是在选择列表中使用了
unnest()
:每个
unnest()
调用都会向结果中添加新行

您需要在
from
子句中使用unnest为每个


如果您使用的是Postgres 10或更高版本,这将更简单:

在线示例:


Select  
    Unnest(xpath('//@ActionID',XMLCONTENT)) as ID,
    Unnest(xpath('//@MessageID',XMLCONTENT)) as MessageID,
    Unnest(xpath('//@Operator',XMLCONTENT)) as Operator
with data (xmlcontent) as (
  values ('
  <Actions>
     <Action ActionID="90e0dbef-c23a-4fcd-bfa8-75d8bfa2c9e2" />
     <Action ActionID="6a1998e1-70f1-4611-992a-7a27e2834c35" />
     <Action ActionID="43dd9a91-c6d3-4980-b211-9b3780f04305" />
     <Action ActionID="cdf01821-ac28-45a9-abf8-a7d7c9426518" />
     <Action ActionID="e86fac8a-84e3-41ba-8bee-c7ffd1ac8ee5" />
     <Action ActionID="a68dd878-ba1e-4fd9-b436-cdc15eccffb6" />
     <Action ActionID="cd863a5a-83e9-489e-b24d-ff6638c5b190" />
     <Action ActionID="720ba9c7-b797-4b2e-913e-11ac3ecd7b7f" />
     <Action ActionID="b6b35d0d-938e-45d3-96d1-0c8ca3ad59f3" 
             MessageID="42f40c3a-4426-4506-86c5-222fb03c2114" />
  </Actions>'::xml)
)
select (xpath('//@ActionID', xt.action))[1] as id, 
       (xpath('//@MessageID', xt.action))[1] as message_id
from data
  cross join unnest(xpath('/Actions/Action', xmlcontent)) as xt(action);
select xt.*
from data 
     cross join xmltable ('/Actions/Action'
               passing xmlcontent
               columns id         uuid path '@ActionID', 
                       message_id uuid path '@MessageID'
              ) as xt;