【问题标题】:Oracle 11g xml - return row where child node does not existOracle 11g xml - 返回子节点不存在的行
【发布时间】:2017-08-17 10:04:56
【问题描述】:

我有一个包含 xmlstructure 的表

create table xml_stg_test (rawdata xmltype);

insert into xml_stg_test (rawdata) values (xmltype.createxml('<root>
    <tmp1>
        <val1>123</val1>
    </tmp1>
    <tmp1>
        <val1>234</val1>
        <tmp2>
            <val2>567</val2>
        </tmp2>
    </tmp1>
</root>'));


Select extractvalue(value(rec), '*/val1') test
from xml_stg_test sg, table(xmlsequence(extract(rawdata,'*/tmp1'))) rec;

**TEST**
1 123
2 234

我希望只返回没有子节点 &lt;tmp2&gt; 的节点(即第 1 行)。这可以通过查询来实现吗?也许通过使用成员函数存在节点?

谢谢!

【问题讨论】:

    标签: xml xpath oracle11g


    【解决方案1】:

    您可以改为通过 XMLTable 调用获取您感兴趣的节点值和子节点(如果存在),然后过滤那些没有子节点的行:

    select xt.test
    from xml_stg_test xsg
    cross join xmltable (
      '/root/tmp1'
      passing xsg.rawdata
      columns test number path 'val1',
        filter xmltype path 'tmp2'
    ) xt
    where xt.filter is null;
    
          TEST
    ----------
           123
    

    我将filter 列的数据类型保留为XMLType,但如果您知道类型,则可以从节点获取实际值。不过,这也会捕获空子节点。

    或者你可以直接在 XPath 中过滤:

    select xt.test
    from xml_stg_test xsg
    cross join xmltable (
      'for $n in /root/tmp1 where not(exists($n/tmp2)) return $n'
      passing xsg.rawdata
      columns test number path 'val1',
        filter xmltype path 'tmp2'
    ) xt;
    
          TEST
    ----------
           123
    

    【讨论】:

    • 太棒了,正是我想要的!谢谢!
    【解决方案2】:

    如果我正确理解您的问题。您只想返回叶节点。

    select * from xmltable('//*[not(*)]' passing xmltype('<root>
        <tmp1>
            <val1>123</val1>
        </tmp1>
        <tmp1>
            <val1>234</val1>
            <tmp2>
                <val2>567</val2>
            </tmp2>
        </tmp1>
    </root>'  )
    columns 
     leaf_name varchar2(100) path 'name()', 
     leaf_value varchar2(100) path 'text()' ,
     )
    ;
    

    【讨论】:

      猜你喜欢
      • 2013-09-06
      • 1970-01-01
      • 1970-01-01
      • 2012-09-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-09-06
      相关资源
      最近更新 更多