简体   繁体   中英

Using PL/SQL to extract value of an XML attribute

I have some XML (example given)

<emails>
    <email email_id="user1@email.com"/>
    <email email_id="user2@email.com"/>
    ...
    <email email_id="user8@email.com"/>
<emails>

I want to get the email_id from each email node and put it into a string. eg "user1@email.com, user2@email.com, user3@email.com..."

I am guessing I need to use xmltable in some form but can't work out how to get the values to use other than writing them in a select statement.

You can use XMLTYPE options for this

SQL> set serverout on
SQL> declare
  2    x xmltype := xmltype(
  3    '<emails>
  4      <email email_id="user1@email.com"/>
  5      <email email_id="user2@email.com"/>
  6      <email email_id="user8@email.com"/>
  7  </emails>');
  8
  9    email_list sys.odcivarchar2list := sys.odcivarchar2list();
 10
 11    e varchar2(100);
 12  begin
 13    for i in 1 .. 1000
 14    loop
 15      if x.existSNode('/emails/email['||i||']') > 0 then
 16         e:=    x.extract('/emails/email['||i||']/@email_id').getstringVal();
 17         dbms_output.put_line(e);
 18         email_list.extend;
 19         email_list(i) := e;
 20      else
 21        exit;
 22      end if;
 23    end loop;
 24  end;
 25  /
user1@email.com
user2@email.com
user8@email.com

PL/SQL procedure successfully completed.
SELECT
LISTAGG(emailId, '; ')  
WITHIN GROUP(ORDER BY  emailId) "EmailList"
FROM
(
select emailId 
FROM XMLTABLE('/emails/email'  
         PASSING   
            xmltype('
               <emails>
    <email email_id="user1@email.com"/>
    <email email_id="user2@email.com"/>   
    <email email_id="user8@email.com"/>
      </emails>
            ')
         COLUMNS  

            emailId  varchar2(200)     PATH './@email_id'
     ) xmlt  
 )

;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM