【问题标题】:Parsing XML document in PostgreSQL using XPATH?使用 XPATH 在 PostgreSQL 中解析 XML 文档?
【发布时间】:2017-09-11 02:47:48
【问题描述】:

有没有办法在 PostgreSQL 中使用 XPATH 解析以下 XML 文档以获得所需的输出为

--更正所需的输出

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

对于price 元素。目前,当我运行下面提供的查询时,我得到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

非常感谢您对上述问题提出任何建议。

【问题讨论】:

    标签: xml postgresql xslt xpath xsd


    【解决方案1】:

    问题是没有从前两个价格元素中提取文本。 See discussion. Postgresql 目前仅限于 XPath 1.0,因此我们需要取消嵌套 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
    

    【讨论】:

    • 感谢您的留言。建议的解决方案会起作用,但所需的输出需要参考 pormotion-id 元素。请参阅更新的消息。感谢您的帮助。
    猜你喜欢
    • 2012-01-08
    • 2018-03-12
    • 1970-01-01
    • 1970-01-01
    • 2013-11-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多