2017-09-26 55 views
0

我創建了一個Postgres的表包含XML列:如何在Postgresql中查詢XML列?

id   | integer 
date_created | timestamp with time zone 
hash   | character varying(10) 
original  | xml 
report_name | text 

我插入一個XML字符串:

id |   date_created   | hash |         original         |    report_name     
----+-------------------------------+------------+--------------------------------------------------------------------------+------------------------------------------ 
    9 | 2017-09-26 17:37:16.823251+02 | aaaaaaaaaa | <RequestReportResponse xmlns="http://mws.amazonaws.com/doc/2009-01-01/">+| _GET_XML_ALL_ORDERS_DATA_BY_LAST_UPDATE_ 
    |        |   | <RequestReportResult>             +| 
    |        |   |  <ReportRequestInfo>             +| 
    |        |   |  <ReportType>_GET_XML_ALL_ORDERS_DATA_BY_LAST_UPDATE_</ReportType> +| 
    |        |   |  <ReportProcessingStatus>_SUBMITTED_</ReportProcessingStatus>  +| 
    |        |   |  <EndDate>2017-09-26T13:31:02+00:00</EndDate>      +| 
    |        |   |  <Scheduled>false</Scheduled>          +| 
    |        |   |  <ReportRequestId>50064017435</ReportRequestId>     +| 
    |        |   |  <SubmittedDate>2017-09-26T13:31:02+00:00</SubmittedDate>   +| 
    |        |   |  <StartDate>2017-09-26T13:31:02+00:00</StartDate>     +| 
    |        |   |  </ReportRequestInfo>            +| 
    |        |   | </RequestReportResult>            +| 
    |        |   | <ResponseMetadata>             +| 
    |        |   |  <RequestId>e092cdbe-2978-4064-a5f6-129b88322b02</RequestId>   +| 
    |        |   | </ResponseMetadata>             +| 
    |        |   | </RequestReportResponse>            +| 
    |        |   |                   | 

online XPath的測試,我能夠使用相同的XML以檢索ReportRequestId價值,但查詢PostgreSQL的時候我沒有得到任何值回:

select xpath('/RequestReportResponse/RequestReportResult/ReportRequestInfo/ReportRequestId', original) from amazon_output where hash='aaaaaaaaaa'; 

什麼我與XML數據類型不見了?

回答

1

既然你有一個XML命名空間(XMLNS),你需要包括在XPath查詢:

select xpath('/mydefns:RequestReportResponse/mydefns:RequestReportResult/mydefns:ReportRequestInfo/mydefns:ReportRequestId', 
       original, 
       ARRAY[ARRAY['mydefns', 'http://mws.amazonaws.com/doc/2009-01-01/']]) 
from amazon_output where hash='aaaaaaaaaa'; 

Postgres documentation的XPath的方法:

可選的第三個該函數的參數是一個名稱空間映射數組。這個數組應該是一個二維文本數組,其第二軸的長度等於2(即它應該是一個數組數組,每個數組只包含2個元素)。每個數組條目的第一個元素是名稱空間名稱(別名),第二個是名稱空間URI。不需要這個數組中提供的別名與XML文檔中使用的別名相同(換言之,在XML文檔和xpath函數上下文中,別名都是本地的)。

+0

不起作用。我也嘗試了一些你的答案。 – ruipacheco

+1

經過一番實驗,看起來您需要在每個要搜索的元素名稱之前包含名稱空間前綴「mydefns」。我要更新我的答案以反映這一點。讓我知道它是否有效。 –