Vijayanand Settin
Vijayanand Settin

Reputation: 1074

How to write XML attributes as columns to a table in Oracle?

I tried to find solutions over the internet. Some of the stuff I looked at: https://forums.oracle.com/thread/2182669 http://www.club-oracle.com/forums/how-to-insert-data-from-xml-to-table-t2845/

In all these cases, the solution considers XML structure with only nodes and child nodes but not attributes. In fact, one of the solutions suggests transforming the XML into a canonical form with only nodes w/o attributes.

This is a sample of xml structure I am working with:

Sample XML

<rep type="P" title="P List">
<as>
<a id="3" />
<a id="4" />
</as>
</rep>

I am working with oracle client 11.2 and SQL developer

My question is: how to write XML data into a table with attributes also as column values, beside the nodes?

The following worked for me for the temp table, eventually I am going to normalize it into more than one table..

-- Temp table
CREATE TABLE TEMP_Temp1
  (rtype varchar(10),
  title varchar(200),
  aid varchar(10),
  description varchar(100),
  flag varchar(50),
  po char(1));

x is varchar variable of the xml snippet above.

INSERT INTO TEMP_Temp1
    SELECT *
    FROM xmltable( '/rep' passing xmltype (x) columns rtype VARCHAR(10) path '@type' , title VARCHAR(200) path '@title')                                                                   AS xmlr ,
      xmltable( '/rep/a' passing xmltype (x) columns aid    VARCHAR(10) path '@id' , description VARCHAR(100) path '@description' , flag VARCHAR(50) path '@flag' , po CHAR(1) path '@po') AS xmla ;
  END;

Upvotes: 1

Views: 440

Answers (1)

A.B.Cade
A.B.Cade

Reputation: 16905

Maybe you can use INSERT-SELECT with a xmltable.
For example, you can select the data from your xml with a query like this:

Here is a sqlfiddle demo

select X.* 
from xmltable(
'for $i in //rep/as/a return <row>
  {$i/../../@type}
  {$i/../../@title}
  {$i/@id}</row>' passing xmltype('<rep type="P" title="P List">
<as>
<a id="3" />
<a id="4" />
</as>
</rep>')
  columns 
  type varchar2(1) path '@type',
  title varchar2(10) path '@title',
  id number path '@id'
) X

Upvotes: 3

Related Questions