【问题标题】:Postgres XML XPath returns Invalid XPath expressionPostgres XML XPath 返回无效的 XPath 表达式
【发布时间】:2018-02-07 17:39:12
【问题描述】:

晚上好,

我一直在尝试使用 xml 数据查询表。该表有一个 report_id (int) 和 xml_document (xml) 作为其字段。

xml文档是这样构建的:

<document>
<type>INVESTMENT_REQUEST</type>
<cro>
    <userId>1</userId>
    <surname>SUR1</surname>
    <name>NAM1</name>
    <phone>8563</phone>
</cro>
<ma>
    <userId>10</userId>
    <surname>SUR10</surname>
    <name>NAM10</name>
    <phone>6763</phone>
</ma>
<customer>
    <customer_ssn>14</customer_ssn>
    <surname>CSUR2</surname>
    <name>CNAME2</name>
    <birthdate>1985-10-10</birthdate>
    <account_date_opened>2016-05-09</account_date_opened>
    <investment_profiles>
        <investment_profile>
            <profile>4</profile>
            <date_profiled>2016-05-09</date_profiled>
        </investment_profile>
            <investment_profile>
            <profile>3</profile><date_profiled>2017-05-09</date_profiled>
        </investment_profile>
            <investment_profile>
            <profile>3</profile><date_profiled>2017-01-09</date_profiled>
        </investment_profile>
    </investment_profiles>
</customer>
<text>Customer is not averse to risks, and has a huge portfolio of investments.Please advise</text>
</document>

我一直在尝试使用 XPapth 从字段中获取各种值,并且我一直在阅读的教程导致以下命令,它应该为我带来所有客户 ssn:

SELECT UNNEST(xpath('//customer/customer_ssn()',xml_document))::text AS XMLDATA FROM consultation_report;

但这不起作用,它返回一个无效的 XPATH 表达式。有些东西我不明白,我无法理解它是什么。我已经逐个字母地遵循示例。

如果我在没有 () 的情况下运行命令,

SELECT UNNEST(xpath('//customer/customer_ssn',xml_document))::text AS XMLDATA FROM consultation_report;

返回:

<customer_ssn>12</customer_ssn>
<customer_ssn>13</customer_ssn>
<customer_ssn>14</customer_ssn>

不能用作值。

我误解了什么?另外,如果我想过滤结果,我从哪里开始,p.ex 只带来 customer_ssn 14 的 xml?

(编辑)我已经成功查询:

SELECT * FROM consultation_report WHERE (xpath('//document/customer/customer_ssn',xml_document))[1]::text = '<customer_ssn>14</customer_ssn>'

但我仍然收到以下错误:

    SELECT * FROM consultation_report WHERE (xpath('//document/customer/customer_ssn()',xml_document))[1]::text = '14'

【问题讨论】:

    标签: xml postgresql xpath


    【解决方案1】:

    没有名为customer_ssn 的函数,并且无论如何只能在XPath 1.0 的路径步骤中调用节点测试函数,因此customer_ssn() 将不被接受。也就是说,要返回 customer_ssn 内的文本节点,您应该添加一个节点测试 text()

    //customer/customer_ssn/text()
    

    【讨论】:

    • 我看到的例子叫做实际属性文本(,所以我完全错误的想法!谢谢你这么多,就像一个魅力!
    【解决方案2】:

    但我仍然收到以下错误:

    SELECT * FROM advisor_report WHERE (xpath('//document/customer/customer_ssn()',xml_document))[1]::text = '14'

    您的 xpath 表达式中缺少 text() 函数:

    SELECT * 
    FROM consultation_report 
    WHERE (xpath('//document/customer/customer_ssn/text()',xml_document))[1]::text = '14'
    

    【讨论】:

    • 谢谢您的回答,您确实是正确的。但是我只能接受 1 个答案,我会选择 @har07,因为他早些时候并解释了问题所在。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-10-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-05-03
    • 2014-11-16
    • 2017-03-06
    相关资源
    最近更新 更多