简体   繁体   中英

How to convert from XML to table?

29I have this XML string:

<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>

and I need generate a table (or a rowset) like this:

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

Got it using xpath with @ to get attribute value and 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM