2017-09-11 144 views
2

有一种方法来解析使用XPATH,以获得期望的输出PostgreSQL中下面的XML文档作为解析XML文档使用XPATH?

--Corrected为price元件所需的输出

promotion-id price new-promotion null new-promotion null new-promotion 300

。目前,当我运行下面提供的查询,我得到300作为输出。我的问题是我的查询忽略其<price xsi:nil="true"/>结构中的价格因素。

有没有办法将null作为<price xsi:nil="true"/>类型结构的价格元素的结果?

我的代码是这样的:

WITH x AS (SELECT 
'<promotions xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> 
    <promotion promotion-id="old-promotion"> 
     <enabled-flag>true</enabled-flag> 
     <searchable-flag>false</searchable-flag> 
    </promotion> 
    <promotion promotion-id="new-promotion"> 
     <enabled-flag>false</enabled-flag> 
     <searchable-flag>false</searchable-flag> 
     <exclusivity>no</exclusivity> 
     <price xsi:nil="true"/> 
     <price xsi:nil="true"/> 
     <price>300</price> 
    </promotion> 
</promotions>'::xml AS t 
) 
SELECT unnest(xpath('//price/text()', node))::text 
FROM (SELECT unnest(xpath('/promotions/promotion', t)) AS node FROM x) sub 

对上述问题的任何建议高度赞赏。

回答

1

的问题是,不存在将被从所述第一2个价元素提取的文本。 See discussion. PostgreSQL是目前仅限于XPath 1.0所以我们需要UNNEST的XML片段,然后分别将它们转换为文本。

WITH x AS (SELECT 
'<promotions xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> 
    <promotion promotion-id="old-promotion"> 
     <enabled-flag>true</enabled-flag> 
     <searchable-flag>false</searchable-flag> 
    </promotion> 
    <promotion promotion-id="new-promotion"> 
     <enabled-flag>false</enabled-flag> 
     <searchable-flag>false</searchable-flag> 
     <exclusivity>no</exclusivity> 
     <price xsi:nil="true"/> 
     <price xsi:nil="true"/> 
     <price>300</price> 
    </promotion> 
</promotions>'::xml AS t 
) 
SELECT (xpath('@promotion-id',node))[1]::text AS "promotion-id", 
     (xpath('/price/text()', 
       unnest(xpath('price',node)) 
     ))[1]::text AS price 
    FROM (SELECT unnest(xpath('/promotions/promotion', t)) AS node FROM x) sub 
+0

感谢你的消息。建议的解决方案可能会奏效,但所需的输出需要参考pormotion-id元素。请参阅更新的消息。感谢你的帮助。 –