2016-01-29 35 views
2

我一直試圖從XML中提取值,方法與@Erwin Brandstetter用已接受的答案回答了幾次,但它不適用於我:Postgresql:使用xpath從XML列中提取數據

根據this postthis post這應該工作,但我只是得到一個結果:

WITH x AS (SELECT 
    '<Attributes xmlns="http://www.gis34.dk"> 
     <bemaerkning displayName="Bemærkning">Beatrix</bemaerkning> 
     <billede displayName="Billede">https://vignette.wikia.nocookie.net/killbill/images/3/39/The_Bride.jpg</billede> 
    </Attributes>'::xml AS t 
) 

SELECT xpath('/Attributes/bemaerkning/text()', t) as comment 
FROM x 

結果: (預期:{我的評論})

comment 
xml[] 
------- 
{} 

我的數據庫版本:

PostgreSQL 9.1.3 on x86_64-unknown-linux-gnu, compiled by gcc-4.5.real (Ubuntu/Linaro 4.5.2-8ubuntu4) 4.5.2, 64-bit 

任何人有一個想法?

+0

檢查這一項:

SELECT (xpath('/g:Attributes/g:bemaerkning/text()', t, array[array['g','http://www.gis34.dk']])[1] as comment FROM x 

注意周圍的函數調用括號:http://stackoverflow.com/questions/17799790/using-xpath-to-extract-data-from-an-xml-column-in-postgres – har07

+0

@ har07,這個鏈接是我的問題中的兩個參考之一。 .. :-) – Ambran

回答

1

您的XML定義了一個名稱空間,並且該名稱空間必須在xpath表達式中使用。

SELECT xpath('/g:Attributes/g:bemaerkning/text()', t, array[array['g','http://www.gis34.dk']]) as comment 
FROM x 

注意第三個參數passes a two-dimensional array of namespace mappings

xpath()函數返回一組元素。如果你知道你只能得到一個單一的元素(或永遠只想要第一個),你剛剛返回數組的第一個元素:(xpath(...))

+0

太好了。還有一件事,是否可以在沒有圍繞它們的花括號的情況下檢索文本? – Ambran

+1

@Ambran:'xpath()'返回一個數組,只是使用第一個元素。查看我的編輯 –

+0

再次感謝:-) – Ambran