最近在研究Oracle PLSQL中對於XML的系列操作。結合工作中使用的知識和參考資料整理出以下相關內容:
CREATE OR REPLACE DIRECTORY xml_dir AS 'd:\app\xml'; DROP SEQUENCE seq_filename; CREATE SEQUENCE seq_filename MINVALUE 10000 MAXVALUE 99999 INCREMENT BY 1 START WITH 10000 NOCYCLE;
DECLARE v_filename Varchar2(50) := 'Empmsg'||to_char(seq_filename.nextval)||'.xml'; xml_str clob; xml_file utl_file.file_type; offset number; buffer varchar2(32767); buffer_size number; BEGIN offset := 1; buffer_size := 3000; xml_file := utl_file.fopen('XML_DIR', v_filename, 'w'); xml_str := dbms_xmlquery.getxml('select empno, ename, job, mgr, hiredate, sal, comm, deptno from emp'); while (offset < dbms_lob.getlength(xml_str)) loop buffer := dbms_lob.substr(xml_str, buffer_size, offset); utl_file.put(xml_file, buffer); utl_file.fflush(xml_file); offset := offset + buffer_size; end loop; utl_file.fclose(xml_file); END;
DECLARE v_filename Varchar2(50) := 'Empmsg'||to_char(scott.seq_filename.nextval)||'.xml'; xml_str clob; xml_file utl_file.file_type; offset number; buffer varchar2(32767); buffer_size number; BEGIN offset := 1; buffer_size := 3000; xml_file := utl_file.fopen('XML_DIR', v_filename, 'w'); SELECT XMLElement("DEPARTMENT" , XMLAttributes( department_id as "ID" , department_name as "NAME" ) , XMLElement("EMPLOYEES" , (SELECT XMLAgg( XMLElement("EMPLOYEE" , XMLForest(employee_id as "ID" ,first_name||' '||last_name as "NAME" ) ) ) FROM hr.employees emp WHERE emp.department_id = dept.department_id ) ) ).getclobval() INTO xml_str FROM hr.departments dept WHERE department_id = 20; while (offset < dbms_lob.getlength(xml_str)) loop buffer := dbms_lob.substr(xml_str, buffer_size, offset); utl_file.put(xml_file, buffer); utl_file.fflush(xml_file); offset := offset + buffer_size; end loop; utl_file.fclose(xml_file); END;--XMLElement: 將一個關系值轉換為XML元素的函數,格式為<elementName>值</elementName>
SET TRIMSPOOL ON SET TERMOUT ON SET FEEDBACK OFF SET VERIFY OFF SET ECHO OFF SET PAGESIZE 999 SET HEAD OFF SET HEADING OFF SET LONG 5000 spool c:\a.xml SELECT XMLElement("DEPARTMENT" , XMLAttributes( department_id as "ID" , department_name as "NAME" ) , XMLElement("EMPLOYEES" , (SELECT XMLAgg( XMLElement("EMPLOYEE" , XMLForest(employee_id as "ID" ,first_name||' '||last_name as "NAME" ) ) ) FROM employees emp WHERE emp.department_id = dept.department_id ) ) ) a FROM departments dept WHERE department_id = 10; spool off 二 如何存儲XML文件內容:三 如何解析XML內容:四 XMLTABLE用法: to be continue... ---------------------------------- By Dylan.