如何在Oracle中使用XMLTable来实现以下XML

时间:2016-02-04 11:06:41

标签: xml oracle oracle11g namespaces xmltable

我在Oracle的一个列中有XML,存储为CLOB类型。我的目的是解析此XML并检索与感兴趣的列相对应的数据。这是XML结构:

<ns:ABCDE xmlns:ns="http://www.something.com/something" xmlns:mno="http://www.somethingelse.com/05"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
xsi:type="ns:ABCDE"> 

<GGGGG> 
    <G1>G1_val</G1> 
    <G2>G2_val</G2> 
    <G3>G3_val</G3>
</GGGGG>
<PPPPP>
...
</PPPP>

</ns:ABCDE>

这是我的SQL代码:

    select x.*,p.*
    from ppp p ,xmltable(

    xmlnamespaces(default   'ABCDE',
    'http://www.something.com/something' as "ns",
    'http://www.somethingelse.com/05' as "mno", 
'http://www.w3.org/2001/XMLSchema-instance' as "xsi",
    'ns:ABCDE' as "type"
            ),    

    '/ns:ABCDE'
    PASSING xmltype(p.someCLOB_column)
    COLUMNS G1 varchar(32) PATH '/GGGGG'

    ) x  

但是,在运行SQL之后,它不会显示任何错误,但也不会获取任何记录。我期望得到“G1_val”作为此查询的结果。

代码出错的地方在哪里?我对xml /名称空间不太熟悉。

感谢。

1 个答案:

答案 0 :(得分:1)

我不确定你为什么没有看到任何东西;我看错了,但这可能取决于我认为的Oracle版本,或者真正的XML和代码的差异。默认命名空间使问题混乱,不应该存在;并且GGGGG的路径不需要前导斜杠:

with ppp (someCLOB_column) as (
  select '<ns:ABCDE xmlns:ns="http://www.something.com/something" xmlns:mno="http://www.somethingelse.com/05"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:type="ns:ABCDE"> 
<GGGGG> 
    <G1>G1_val</G1> 
    <G2>G2_val</G2> 
    <G3>G3_val</G3>
</GGGGG>
<PPPPP>...</PPPPP>
</ns:ABCDE>' from dual
)
select x.g1
from ppp p
cross join xmltable(
  xmlnamespaces(--default 'ABCDE',
    'http://www.something.com/something' as "ns",
    'http://www.somethingelse.com/05' as "mno", 
    'http://www.w3.org/2001/XMLSchema-instance' as "xsi",
    'ns:ABCDE' as "type"
  ),    
  '/ns:ABCDE'
  PASSING xmltype(p.someCLOB_column)
  COLUMNS G1 varchar(32) PATH 'GGGGG'
) x 
/

G1                             
--------------------------------
G1_valG2_valG3_val              

您可能想要个别值:

select x.g1, x.g2, x.g3, x.ppppp
from ppp p
cross join xmltable(
  xmlnamespaces(--default 'ABCDE',
    'http://www.something.com/something' as "ns",
    'http://www.somethingelse.com/05' as "mno", 
    'http://www.w3.org/2001/XMLSchema-instance' as "xsi",
    'ns:ABCDE' as "type"
  ),    
  '/ns:ABCDE'
  PASSING xmltype(p.someCLOB_column)
  COLUMNS G1 varchar(8) PATH 'GGGGG/G1',
    G2 varchar(8) PATH 'GGGGG/G2',
    G3 varchar(8) PATH 'GGGGG/G3',
    PPPPP varchar2(8) PATH 'PPPPP'
) x 
/

G1       G2       G3       PPPPP  
-------- -------- -------- --------
G1_val   G2_val   G3_val   ...