从Oracle DB读取XML作为<column1> column2 <column1>每行</column1> </column1>

时间:2014-05-22 15:06:13

标签: sql xml oracle oracle11g

表格消息

    ID PARAM_NAME PARAM_VALUE             
     
     1 from       blah@example.org          
     2 to         pew@example.org           
     3 customer   John Doe                  
     4 order      100500                    
     5 status     yes   

结果是简单的xml字符串

<?xml version="1.0" encoding="UTF-8"?>
<data>
    <from>blah@example.org</from>
    <to>pew@example.org</to>
    <customer>John Doe</customer>
    <order>100500</order>
    <status>yes</status>
</data>
SELECT XMLELEMENT(m.param_name, m.param_value) AS data 
FROM message m;

不起作用。

1 个答案:

答案 0 :(得分:0)

因为XML元素的名称是标识符,所以您需要使用evalname函数:

with test_data as (
  select 1 id, 'from'     param_name, 'blah@example.org' param_value from dual union all
  select 2 id, 'to'       param_name, 'pew@example.org'  param_value from dual union all
  select 3 id, 'customer' param_name, 'John Doe'         param_value from dual union all
  select 4 id, 'order'    param_name, '100500'           param_value from dual union all
  select 5 id, 'status'   param_name, 'yes'              param_value from dual   
)
select 
  xmlelement("data", 
    xmlagg(
      xmlelement( evalname(param_name), param_value)
    )
  )
from test_data
order by id