如何检查XML文档中是否存在给定节点

时间:2014-10-02 10:53:33

标签: sql xml oracle plsql

如何检查XML文档中是否存在给定节点?

XML示例:

<order>
    <desc>
        <name>Test name</name>
        <code>Test code</code>
    </desc>
    <suborders>
        <item>
            <id>1000</id>
        </item>
        <item>
            <id>2000</id>
        </item>
    </suborders>
    <options>
       <item/>
    </options>
</order>

如果存在任何子订单项,如何检入PL / SQL?

我试过这样:

DECLARE
   myxml CLOB := ...
BEGIN 
   SELECT extractValue(XMLTYPE(myxml), '/order/suborders/item[1]') 
     INTO firstSuborder 
    FROM DUAL;

   IF (firstSuborder IS NULL) THEN
          dbms_output.put_line('suborder doesnt exist');
   END IF;
END;

但我得到ORA-19025: EXTRACTVALUE returns value of only one node

1 个答案:

答案 0 :(得分:2)

您可以使用existsnode,这里是文档http://docs.oracle.com/cd/B19306_01/appdev.102/b14259/xdb04cre.htm#i1032763

declare
  OBJECT_VALUE xmltype := xmltype(q'{<order>
    <desc>
        <name>Test name</name>
        <code>Test code</code>
    </desc>
    <suborders>
        <item>
            <id>1000</id>
        </item>
        <item>
            <id>2000</id>
        </item>
    </suborders>
    <options>
       <item/>
    </options>
</order>}');

  node_exists pls_integer;

begin

  select existsNode(OBJECT_VALUE, '/order/suborders/item[1]') into node_exists from dual;
  dbms_output.put_line('exists: ' || to_char(node_exists));
end;