Postgres XML XPath返回无效的XPath表达式

时间:2018-02-07 01:18:34

标签: xml postgresql xpath

晚上好,

我一直在尝试使用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'

2 个答案:

答案 0 :(得分:1)

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

//customer/customer_ssn/text()

答案 1 :(得分:1)

  

但我仍然收到错误:

     

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

您错过了xpath表达式中的text()函数:

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