2016-12-26 69 views
0

我需要從XML數據導入到PostgreSQLXML到PostgreSQL表的查詢

XML是什麼樣子:

<?xml version="1.0" encoding="UTF-8"?> 
<HouseStateStatuses> 
    <HouseStateStatus HOUSESTID="0" NAME="descripton_1" /> 
    <HouseStateStatus HOUSESTID="1" NAME="descripton_2" /> 
    <HouseStateStatus HOUSESTID="2" NAME="descripton_3" /> 
    <HouseStateStatus HOUSESTID="3" NAME="descripton_4" /> 
    <HouseStateStatus HOUSESTID="4" NAME="descripton_5" /> 
</HouseStateStatuses> 

我想將數據放在一個PostgreSQL表:

HOUSESTID |NAME 
1   |descripton_1 
2   |descripton_2 
3   |descripton_3 

謝謝!

+0

如果你去大寫的列名稱,你可能會後悔, – Jasen

+0

@Jasen這是我有,不能改變 –

回答

0
with t(x) as (values('<?xml version="1.0" encoding="UTF-8"?> 
<HouseStateStatuses> 
    <HouseStateStatus HOUSESTID="0" NAME="descripton_1" /> 
    <HouseStateStatus HOUSESTID="1" NAME="descripton_2" /> 
    <HouseStateStatus HOUSESTID="2" NAME="descripton_3" /> 
    <HouseStateStatus HOUSESTID="3" NAME="descripton_4" /> 
    <HouseStateStatus HOUSESTID="4" NAME="descripton_5" /> 
</HouseStateStatuses>'::xml)) 
select 
    i::text::int as houseid, 
    n::text as name 
from 
    t, 
    unnest(
    xpath('/HouseStateStatuses/HouseStateStatus/@HOUSESTID', x), 
    xpath('/HouseStateStatuses/HouseStateStatus/@NAME', x)) as d(i,n);