如何从Oracle生成XML输出

时间:2014-11-20 10:45:44

标签: xml oracle

一位同事为我写了这个问题:

set linesize 150
set pagesize 0
SET HEADING OFF
SET FEEDBACK OFF
COLUMN C0 NEWLINE

select '<?XML VERSION="1.0"?>'
FROM DUAL
/
SET EMBEDDED ON

select '<row>'                                               C0
, '<field name="orgnr">'||organisatie_nr||'</field>'         C0
, '<field name="orgnaam">'||organisatie_naam_oms||'</field>' C0
, '<field name="orgwnpl">'||woonplaats_oms||'</field>'       C0
, '</row>'                                                   C0
from organisatie_eenheid
/

生成:

<?XML VERSION="1.0"?>                                                                                                                                 
<row>                                                                                                                                                 
<field name="orgnr">910</field>                                                                                                                            
<field name="orgnaam">Dienst Regelingen</field>                                                                                                            
<field name="orgwnpl">ASSEN</field>                                                                                                                        
</row>

在MySQL中mysql -u -p -X 'select organisatie_nr as orgnr, organisatie_naam_oms as orgnaam, woonplaats_oms as orgwnpl from organisatie_eenheid;'会产生类似的结果:

<?XML VERSION="1.0"?>
<resultset>
  <row>
  <field name="orgnr">910</field>
  <field name="orgnaam">Dienst Regelingen</field>
  <field name="orgwnpl">ASSEN</field>
</row>
</resultset>              

我知道Oracle也可以生成XML,但由于我从不使用Oracle,因此我不知道语法。

哪个Oracle查询可以生成与MySQL相同的输出?

1 个答案:

答案 0 :(得分:1)

尝试这样的事情(取自文档):

SELECT XMLSerialize(
         DOCUMENT
         SYS_XMLGEN(
           dept_t(department_id,
                  department_name,
                  d.location_id,
                  cast(MULTISET
                       (SELECT emp_t(e.employee_id, e.last_name,
                                     e.job_id, e.manager_id, e.hire_date,
                                     e.salary, e.commission_pct)
                          FROM hr.employees e
                          WHERE e.department_id = d.department_id)
                       AS emplist_t)))
         AS CLOB)
  AS deptxml
  FROM hr.departments d WHERE department_id = 10 OR department_id = 20;

您可以从文档中了解有关如何将查询转换为XML的更多信息:

https://docs.oracle.com/cd/E11882_01/appdev.112/e23094/xdb13gen.htm#ADXDB5041