如何从 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 Fiddle

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;

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 |