I'm trying to extract data in tabular format from an XML field in an Oracle database. Please see sample xml field below:
<?xml version='1.0' encoding='UTF-8'?>
<root>
<element1>
<Header Client_ID="100" Sent_date_time="2015-03-02T9:30:43.808-06:00"/>
<element2>
<element3 UnitPrice="3.2" ItemID="njh1"/>
<element3 UnitPrice="4.1" ItemID="ole5"/>
<element3 UnitPrice="4.6" ItemID="usd3"/>
<element3 UnitPrice="8.2" ItemID="eor9"/>
<element3 UnitPrice="2.9" ItemID="abc8"/>
<element3 UnitPrice="5.1" ItemID="gfd3"/>
<element3 UnitPrice="4.9" ItemID="kdu0"/>
<element3 UnitPrice="6.1" ItemID="uso8"/>
</element2>
</element1>
</root>
My aim is to query the itemID and UnitPrice fields from the xml field above in the format shown below:
ItemID UnitPrice
njh1 3.2
ole5 4.1
usd3 4.6
eor9 8.2
abc8 2.9
gfd3 5.1
kdu0 4.9
uso8 6.1
I'm fairly new to querying data from xml fields. I have tried using the getStringVal, but all I get is one single long string. Please advise on a solution. Please note that I don't have dba rights to this database.
Thank you
You have to use XMLTABLE function for this.
Oracle 11g R2 Schema Setup :
create table xml_test(
xml_col varchar2(2000)
);
insert into xml_test values(
'<?xml version=''1.0'' encoding=''UTF-8''?>
<root>
<element1>
<Header Client_ID="100" Sent_date_time="2015-03-02T9:30:43.808-06:00"/>
<element2>
<element3 UnitPrice="3.2" ItemID="njh1"/>
<element3 UnitPrice="4.1" ItemID="ole5"/>
<element3 UnitPrice="4.6" ItemID="usd3"/>
<element3 UnitPrice="8.2" ItemID="eor9"/>
<element3 UnitPrice="2.9" ItemID="abc8"/>
<element3 UnitPrice="5.1" ItemID="gfd3"/>
<element3 UnitPrice="4.9" ItemID="kdu0"/>
<element3 UnitPrice="6.1" ItemID="uso8"/>
</element2>
</element1>
</root>'
);
Query :
select cols.ItemID, cols.UnitPrice
from xml_test x,
xmltable('root/element1/element2/element3'
passing xmltype(x.xml_col)
columns ItemID varchar2(10) path '@ItemID',
UnitPrice varchar2(10) path '@UnitPrice'
) cols;
Results :
| ITEMID | UNITPRICE |
|--------|-----------|
| njh1 | 3.2 |
| ole5 | 4.1 |
| usd3 | 4.6 |
| eor9 | 8.2 |
| abc8 | 2.9 |
| gfd3 | 5.1 |
| kdu0 | 4.9 |
| uso8 | 6.1 |
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.