繁体   English   中英

如何从Oracle数据库中的XML字段中以表格格式提取数据?

[英]How to extract data in tabular format from XML field in Oracle database?

我正在尝试从Oracle数据库中的XML字段以表格格式提取数据。 请参阅下面的示例xml字段:

<?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>

我的目标是以下面显示的格式从上面的xml字段查询itemID和UnitPrice字段:

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

我是从xml字段查询数据的新手。 我尝试过使用getStringVal,但我得到的只是一个长字符串。 请告知解决方案。 请注意,我没有此数据库的dba权限。

谢谢

您必须使用XMLTABLE函数。

SQL小提琴

Oracle 11g R2架构设置

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>'
  );

查询

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;

结果

| 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 |

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM