如何从XML转换为表格?

时间:2015-03-05 13:19:53

标签: sql xml postgresql xml-parsing

29我有这个XML字符串:

<CP>
  <V PV="1.29" PT="1.29" PB="1.29" ML="0.0" OB="Reg" />
  <V PV="0.77" PT="1.29" PB="1.29" ML="0.6" OB="Reg" />
  <V PV="0.77" PT="1.29" PB="0.65" ML="0.645" OB="Reg" />
</CP>

我需要像这样生成一个表(或行集):

PV       PT      PB       ML      OB
numeric  numeric numeric  numeric text
-------- ------- -------- ------- ----
1.29     1.29    1.29     0.0     Reg 
0.77     1.29    1.29     0.6     Reg
0.77     1.29    0.65     0.645   Reg

Postgres 9.x

1 个答案:

答案 0 :(得分:1)

使用xpath@一起获取属性值和unnest

select cast(cast((xpath('/V/@PV', node))[1] as text) AS numeric) as PV,
       cast(cast((xpath('/V/@PT', node))[1] as text) AS numeric) as PT,
       cast(cast((xpath('/V/@PB', node))[1] as text) AS numeric) as PB,
       cast(cast((xpath('/V/@ML', node))[1] as text) AS numeric) as ML,
       cast(cast((xpath('/V/@OB', node))[1] as text) AS text   ) as OB
from unnest(xpath('/CP/V',
'<CP><V PV="1.29" PT="1.29" PB="1.29" ML="0.0" OB="Reg" /><V PV="0.77" PT="1.29" PB="1.29" ML="0.6" OB="Reg" /><V PV="0.77" PT="1.29" PB="0.65" ML="0.645" OB="Reg" /></CP>'
)) node