2009-06-12 64 views
33

我有以下內容的XMLTYPE:的Oracle PL/SQL:遍歷XMLTYPE節點

<?xml version="1.0"?> 
    <users> 
     <user> 
      <name>user1</name> 
     </user> 
     <user> 
      <name>user2</name> 
     </user> 
     <user> 
      <name>user3</name> 
     </user> 
    </users> 

我怎麼能環在PL/SQL通過所有元素 「用戶」?謝謝

回答

18

您可以通過循環使用EXTRACTXMLSequence元素(拆分XML爲不同的塊 - 在這裏用戶)這樣的:

SQL> SELECT extractvalue(column_value, '/user/name') "user" 
    2 FROM TABLE(XMLSequence(XMLTYPE(
    3     '<?xml version="1.0"?> 
    4      <users> 
    5       <user> 
    6        <name>user1</name> 
    7       </user> 
    8       <user> 
    9        <name>user2</name> 
10       </user> 
11       <user> 
12        <name>user3</name> 
13       </user> 
14      </users>').extract('/users/user'))) t; 

user 
-------- 
user1 
user2 
user3 
+0

非常感謝你! – Samson 2012-04-26 10:56:59

15

您可以使用XQuery。查看下面的select語句。 v_xml_doc是包含XML數據的XMLTYPE變量。

select name 
from XMLTable('for $i in /users/user 
          return $i' 
          passing v_xml_doc 
          columns name varchar2(200) path 'name' 
       ) 
12

如何:

PROCEDURE xmltest IS 
    v_userlist XMLType; 
    v_count NUMBER(38) := 1; 
BEGIN 
    /* define XML variable */ 
    v_userlist := XMLType('<?xml version="1.0"?> 
    <users> 
     <user> 
      <name>user1</name> 
     </user> 
     <user> 
      <name>user2</name> 
     </user> 
     <user> 
      <name>user3</name> 
     </user> 
    </users>'); 

    /* for each user, print out their name (each element can be extracted using xpath '//user[1]' '//user[2]' etc) */ 
    WHILE v_userlist.existsNode('//user[' || v_count || ']') = 1 LOOP 
    dbms_output.put_line(v_userlist.extract('//user[' || v_count || ']/name/text()').getStringVal()); 
    v_count := v_count + 1; 
    END LOOP; 
END; 
-2
ITS VERY GOOD!! 

CADENA CLOB; 
BEGIN 
    SELECT CASE 
      WHEN EXISTSNODE (:NEW.MENSAJE, '/Body') <> 0 THEN 'ERROR' 
      ELSE NULL 
      END 
    INTO :NEW.DESCRIPCION_ERROR 
    FROM DUAL; 

    CADENA := :NEW.MENSAJE.EXTRACT ('/Body/xmlOriginal/text()').getStringVal(); 
    CADENA := REPLACE (CADENA, '&lt;', '<'); 
    CADENA := REPLACE (CADENA, '&gt;', '>'); 
1
select xt.* from xmltable('/users/user' passing xmltype('<users> 
    <user> 
     <name>user1</name> 
    </user> 
    <user> 
     <name>user2</name> 
    </user> 
    <user> 
     <name>user3</name> 
    </user> 
</users>') columns name varchar2(10) path 'name') xt