Skip navigation.

How does one map relational data from tables to XML?

If you're using Oracle 8i, use the DBMS_XMLQUERY and DBMS_XMLSAVE JAVA based packages. For Oracle 9i, use the C-based package DBMS_XMLGEN.

Look at the following Oracle 9i code example:

connect scott/tiger
set serveroutput on
DECLARE
        Ctx    DBMS_XMLGEN.ctxHandle;   -- Var's to convert SQL output to XML
        xml    clob;
        emp_no NUMBER := 7369;
        xmlc   varchar2(4000);          -- Var's required to convert lob to varchar
        off    integer := 1;
        len    integer := 4000;
BEGIN
        Ctx := DBMS_XMLGEN.newContext('SELECT * FROM emp WHERE empno = '||emp_no);
        DBMS_XMLGen.setRowsetTag(Ctx, 'EMP_TABLE');
        DBMS_XMLGen.setRowTag(Ctx, 'EMP_ROW');
        DBMS_XMLGEN.closeContext(Ctx);
        xml := DBMS_XMLGEN.getXML(Ctx);

        DBMS_LOB.READ(xml, len, off, xmlc);   -- Display first part on screen
        DBMS_OUTPUT.PUT_LINE(xmlc);
END;
/

The same results can be achieved using SQLX (see http://sqlx.org/). Some of the SQLX functions are XMLElement(), XMLForest(), XMLSequence(), etc. Look at this example.

set long 32000
SELECT XMLELEMENT("EMP_TABLE",
        (select XMLELEMENT("EMP_ROW",
                   XMLFOREST(empno, ename, job, mgr, hiredate, sal, deptno)
                )
         from   emp
         where  empno = 7369))
from dual;

An older Oracle 8i example:

connect scott/tiger
set serveroutput on
DECLARE
	Ctx    DBMS_XMLQuery.ctxType;	-- Var's to convert SQL output to XML
	xml    clob;
	emp_no NUMBER := 7369;
	xmlc   varchar2(4000);		-- Var's required to convert lob to varchar
	off    integer := 1;
	len    integer := 4000;
BEGIN
	Ctx := DBMS_XMLQuery.newContext('SELECT * FROM emp WHERE empno = :empno');
	DBMS_XMLQuery.setBindValue(Ctx, 'empno', emp_no);
	xml := DBMS_XMLQuery.getXML(Ctx);
	DBMS_XMLQuery.closeContext(Ctx);

	DBMS_LOB.READ(xml, len, off, xmlc);   -- Display first part on screen
	DBMS_OUTPUT.PUT_LINE(xmlc);
END;
/