вторник, 16 марта 2010 г.

Transform Well (Table) Formatted XML into Table in Oracle

Let we have table-like xml with custom namespace and we want to transform it to the table (resultset)
to be used in select query.

Let we have function getXML() that returns the following XMLType value:
      <datas1:employmenttypeslist xmlns:datas1="http://mynamespace/">
         <datas1:employmenttypes>
            <datas1:id>676</datas1:id>
            <datas1:code>NOT_WORK</datas1:code>
            <datas1:text>Not working</datas1:text>
         </datas1:employmenttypes>
         <datas1:employmenttypes>
            <datas1:id>677</datas1:id>
            <datas1:code>OWN_BUSINESS</datas1:code>
            <datas1:text>Own business</datas1:text>
         </datas1:employmenttypes>
         <datas1:employmenttypes>
            <datas1:id>678</datas1:id>
            <datas1:code>PENSIONER</datas1:code>
            <datas1:text>Pensioner</datas1:text>
         </datas1:employmenttypes>
      </datas1:employmenttypeslist>

So, to transform the XMLType into a table we can use several methods.

Method #1
select 
extractValue(xmlt.COLUMN_VALUE,'*/p:id','xmlns:p="http://mynamespace/"') as id,
extractValue(xmlt.COLUMN_VALUE,'*/p:code','xmlns:p="http://mynamespace/"') as code,
extractValue(xmlt.COLUMN_VALUE,'*/p:text','xmlns:p="http://mynamespace/"') as text

from

TABLE(XMLSEQUENCE(

EXTRACT(
(
    select getXML() from dual
),
'/*/*'
)

)) xmlt



Method #2
select *
FROM XMLTABLE(XMLNAMESPACES ('http://mynamespace/' AS "p"),'/*/*'
         PASSING 
            getXML()
         COLUMNS
            --describe columns and path to them:
            id varchar2(10)    PATH '/*/p:id',
            code varchar2(10)  PATH '/*/p:code',
            text varchar2(255) PATH '/*/p:text'
     ) xmlt
;

Комментариев нет:

Отправить комментарий