通过查询xml到postgresql表

时间:2016-12-26 10:00:17

标签: xml postgresql

我需要从xml导入数据到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

谢谢!

1 个答案:

答案 0 :(得分: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);