XML technologies / Oracle & XML / Working with XML / Generating XML from relational data
(Excerpt from "Oracle PL/SQL: Das umfassende Handbuch", chapter 16 "Arbeiten mit XML", by Jürgen Sieben)
Oracle offers many ways to generate XML from relational or object-relational data:
SQL/XML functions
XQuery
converting object types to XML through
dbms_xmlgenorsys_xmlgen(deprecated from version 12c)manual generation through DOM tree programming
manual creation of an XML string followed by casting to
XMLTypethrough a constructor
I will cover only the most common approaches. If you want to choose suitable techniques now, also read the “New features in version 12c” box.
The SQL/XML standard
One of Oracle Database’s most surprising XML capabilities is dynamically generating XML from relational data with a simple XML query. The scalar and aggregate functions required have existed since version 9, essentially since XML was introduced. Oracle’s method of producing XML from SQL is now part of the ISO SQL standard and is also supported by IBM DB2 and Microsoft SQL Server. Let us look at a first example:
select xmlelement("Mitarbeiter",
xmlattributes(empno "id",
hiredate "einstellDatum"),
xmlforest(initcap(ename) "Name",
initcap(job) "Beruf",
to_char(sal, '999G990D00L') "Gehalt")
) resultat
from emp;
RESULTAT
----------------------------------------------------------------
<Mitarbeiter id="7369" einstellDatum="1980-12-17"><Name>Smith</N
<Mitarbeiter id="7499" einstellDatum="1981-02-20"><Name>Allen</N
<Mitarbeiter id="7521" einstellDatum="1981-02-22"><Name>Ward</Na
<Mitarbeiter id="7566" einstellDatum="1981-04-02"><Name>Jones</N
<Mitarbeiter id="7654" einstellDatum="1981-09-28"><Name>Martin</
<Mitarbeiter id="7698" einstellDatum="1981-05-01"><Name>Blake</N
<Mitarbeiter id="7782" einstellDatum="1981-06-09"><Name>Clark</N
<Mitarbeiter id="7788" einstellDatum="1987-04-19"><Name>Scott</N
<Mitarbeiter id="7839" einstellDatum="1981-11-17"><Name>King</Na
<Mitarbeiter id="7844" einstellDatum="1981-09-08"><Name>Turner</
<Mitarbeiter id="7876" einstellDatum="1987-05-23"><Name>Adams</N
<Mitarbeiter id="7900" einstellDatum="1981-12-03"><Name>James</N
<Mitarbeiter id="7902" einstellDatum="1981-12-03"><Name>Ford</Na
<Mitarbeiter id="7934" einstellDatum="1982-01-23"><Name>Miller</
14 Zeilen ausgewählt.One complete, slightly formatted row looks like this:
<Mitarbeiter id="7369" einstellDatum="1980-12-17">
<Name>Smith</Name>
<Beruf>Clerk</Beruf>
<Gehalt>800,00€</Gehalt>
</Mitarbeiter>Code example: generating XML through SQL/XML
Before examining the example, remember that SQL/XML functions are ordinary scalar and aggregate functions, syntactically equivalent to lower or sum and usable the same way, even combined with “normal” scalar functions. The example shows that xmlelement evidently creates XML elements. It accepts several parameters. I pass two: first the result of xmlattributes and second the result of xmlforest. The first creates attributes directly on the parent element; xmlforest creates a group of children beneath the element where it is called. Double quotes make element names case-sensitive, as with aliases. Some details are interesting too: scalar functions can be nested as elsewhere in SQL. I did so when formatting the name and job with initcap and the salary with to_char. Oracle also seems to know how to convert dates to XML, since column hiredate is passed as date without a format mask.
Digression: date functions in SQL/XML
There is a pitfall: SQL/XML functions derive from the ISO standard, in which a date has no time. Thus, the only permitted conversion for a date column is the XML format'yyyy-mm-dd', discarding any time. If the column contains a time, first convert it to a timestamp usingto_timestampor format it usingto_charwith exactly this format mask:'yyyy-mm-dd"T"hh24:mi:ss'. The use of"T"may seem surprising: unlike the ISO standard, XML requires aTbetween date and time. Double quotes insert this literal into the format mask.
Calling these as scalar functions on a table naturally returns the corresponding number of rows. Each contains a valid instance of XMLType and could call its methods. Database versions 10 and 11 greatly expanded SQL/XML’s XML creation functions, adding comments, processing instructions and similar constructs. These are beyond this introduction and will only be mentioned. More important are aggregate functions, which, like ordinary aggregates, turn many input rows into fewer output rows. For example, I want an XML employee list for each department. We will extend the example step by step to achieve that.
First, we wrap our output in another element named Mitarbeiterliste:
select xmlelement("Mitarbeiterliste",
xmlelement("Mitarbeiter",
xmlattributes(empno "id",
hiredate "einstellDatum"),
xmlforest(initcap(ename) "Name",
initcap(job) "Beruf",
to_char(sal, '999G990D00L') "Gehalt")
)
) resultat
from emp;This nesting does not yet group anything; it merely wraps each row in another XML element. Now comes the decisive step:
select xmlelement("Mitarbeiterliste",
xmlagg(
xmlelement("Mitarbeiter",
xmlattributes(empno "id",
hiredate "einstellDatum"),
xmlforest(initcap(ename) "Name",
initcap(job) "Beruf",
to_char(sal, '999G990D00L') "Gehalt")
)
)
) resultat
from emp;
RESULTAT
---------------------------------------------------------------
<Mitarbeiterliste><Mitarbeiter id="7369" einstellDatum="1980-12Aggregate function xmlagg combines its internal results into a group of XML elements (an XML fragment, since multiple top-level elements violate XML syntax ) nested in the enclosing element. We now have one row, but not yet one employee list per department. This final change uses ordinary SQL, not SQL/XML: simply partition the aggregate function using group by. To clarify the result, I also output the department number as attribute abteilung in outer XML element Mitarbeiterliste:
select xmlelement("Mitarbeiterliste",
xmlattributes(deptno "abteilung"),
xmlagg(
xmlelement("Mitarbeiter",
xmlattributes(
empno "id",
hiredate "einstellDatum"),
xmlforest(
initcap(ename) "Name",
initcap(job) "Beruf",
trim(to_char(sal, '999G990D00L')) "Gehalt")
)
)
) resultat
from emp
group by deptno;
RESULTAT
----------------------------------------------------------------
<Mitarbeiterliste abteilung="10"><Mitarbeiter id="7782" einstell
<Mitarbeiterliste abteilung="20"><Mitarbeiter id="7369" einstell
<Mitarbeiterliste abteilung="30"><Mitarbeiter id="7499" einstellA formatted row now looks like this:
<Mitarbeiterliste abteilung="10">
<Mitarbeiter id="7782" einstellDatum="1981-06-09">
<Name>Clark</Name>
<Beruf>Manager</Beruf>
<Gehalt>2.450,00€</Gehalt>
</Mitarbeiter>
<Mitarbeiter id="7839" einstellDatum="1981-11-17">
<Name>King</Name>
<Beruf>President</Beruf>
<Gehalt>5.000,00€</Gehalt>
</Mitarbeiter>
<Mitarbeiter id="7934" einstellDatum="1982-01-23">
<Name>Miller</Name>
<Beruf>Clerk</Beruf>
<Gehalt>1.300,00€</Gehalt>
</Mitarbeiter>
</Mitarbeiterliste>Code example: an extended example
The syntax takes some practice, but these functions make generating XML from relational data quite simple. No programming is needed; a simple select statement suffices, with no object-relational types and their administrative consequences. Arbitrarily complex nesting is possible by generating deeper elements through correlated subqueries within the select statement. Just keep an overview. As queries grow, tracking function calls, attributes, nesting and especially all the parentheses is vital.
The book’s script includes a select statement generating very large XML instances to test SQL/XML performance. In version 10, I found this extremely slow: the sample query took over five minutes. Performance improved greatly in versions 11 and 12c, taking about 20 seconds for the same query. This makes the approach useful in increasingly many situations.
The dbms_xmlgen package and sys_xmlgen
An alternative to SQL/XML is Oracle’s package dbms_xmlgen, which also creates XML instances. It converts tables generically into XML and has a largely equivalent function, sys_xmlgen, for direct use in select queries. At its simplest, convert a table or view and transform the result with XSLT into the required form. The package also handles objects, converting their internal structure into structured XML and potentially making XSLT unnecessary.
Creating simple XML instances
Let us look at a simple example using a query such as:
select *
from emp;To convert this query’s results into XML, we need a PL/SQL block that executes the query and converts the result:
set serveroutput on
declare
ctx dbms_xmlgen.ctxHandle; -- Zeiger auf eine SQL-Abfrage
sql_stmt varchar2(32767);
begin
sql_stmt := 'select * from emp';
ctx := dbms_xmlgen.newContext(sql_stmt);
dbms_output.put_line(dbms_xmlgen.getXml(ctx));
end;
/
<?xml version="1.0"?>
<ROWSET>
<ROW>
<EMPNO>7369</EMPNO>
<ENAME>SMITH</ENAME>
<JOB>CLERK</JOB>
<MGR>7902</MGR>
<HIREDATE>17.12.80</HIREDATE>
<SAL>800</SAL>
<DEPTNO>20</DEPTNO>
</ROW>
<ROW>
<EMPNO>7499</EMPNO>
<ENAME>ALLEN</ENAME>
<JOB>SALESMAN</JOB>
<MGR>7698</MGR>
<HIREDATE>20.02.81</HIREDATE>
<SAL>1600</SAL>
<COMM>300</COMM>
<DEPTNO>30</DEPTNO>
</ROW>
<ROW>
...
</ROW>
</ROWSET>
PL/SQL-Prozedur erfolgreich abgeschlossen.Code example: using dbms_xmlgen
This basic use does not reveal the package’s full power, but illustrates how it works: a root element named ROWSET wraps the query result and each row is wrapped in an element named ROW. To improve the output, set the root and row element names. Column names, currently used for children of ROW, can also be set through column aliases. Here is the improved output:
declare
ctx dbms_xmlgen.ctxHandle;
sql_stmt varchar2(32767);
begin
sql_stmt :=
'select initcap(ename) "Name",
initcap(job) "Beruf",
trim(to_char(sal, ''999G9990D00'')) "Gehalt"
from emp';
ctx := dbms_xmlgen.newContext(sql_stmt);
dbms_xmlgen.setRowSetTag(ctx, 'Mitarbeiterliste');
dbms_xmlgen.setRowTag(ctx, 'Mitarbeiter');
dbms_output.put_line(dbms_xmlgen.getXml(ctx));
end;
/
<?xml version="1.0"?>
<Mitarbeiterliste>
<Mitarbeiter>
<Name>Smith</Name>
<Beruf>Clerk</Beruf>
<Gehalt>800,00</Gehalt>
</Mitarbeiter>
<Mitarbeiter>
<Name>Allen</Name>
<Beruf>Salesman</Beruf>
<Gehalt>1600,00</Gehalt>
</Mitarbeiter>
...
</Mitarbeiterliste>This looks better to me. Let us add the ability to generate columns as attributes by prefixing their aliases with @:
declare
ctx dbms_xmlgen.ctxHandle;
sql_stmt varchar2(32767);
begin
sql_stmt :=
q'[select empno "@id",
to_char(hiredate, 'yyyy-mm-dd') "@einstellDatum",
initcap(ename) "Name",
initcap(job) "Beruf",
trim(to_char(sal, '999G9990D00')) "Gehalt"
from emp]';
ctx := dbms_xmlgen.newContext(sql_stmt);
dbms_xmlgen.setRowSetTag(ctx, 'Mitarbeiterliste');
dbms_xmlgen.setRowTag(ctx, 'Mitarbeiter');
dbms_output.put_line(dbms_xmlgen.getXml(ctx));
end;
/
<?xml version="1.0"?>
<Mitarbeiterliste>
<Mitarbeiter id = "7369" einstellDatum = "17.12.80">
<Name>Smith</Name>
<Beruf>Clerk</Beruf>
<Gehalt>800,00</Gehalt>
</Mitarbeiter>
<Mitarbeiter id = "7499" einstellDatum = "20.02.81">
<Name>Allen</Name>
<Beruf>Salesman</Beruf>
<Gehalt>1600,00</Gehalt>
</Mitarbeiter>
...
</Mitarbeiterliste>Code example: a refined use of dbms_xmlgen
Unlike the corresponding SQL/XML functions, this package does not format dates correctly for XML: unless you explicitly convert them, it uses your session’s default format.
Creating XML instances from object-relational types
Another way to generate nested XML is to prepare hierarchical data with object-relational types. Think of a deeply nested object whose attributes contain tables of further attributes. Prepare such a type using SQL and pass it to package dbms_xmlgen as above to obtain nested XML with the described options. This is not entirely simple and has some limitations. I will show one variant, starting with the object type declarations:
create or replace type "Objekt" is object(
"@art" varchar2(19),
"@erstellungDatum" date,
"@id" number,
"Name" varchar2(128),
"Status" varchar2(7),
"LetzteAenderung" date);
/
Typ wurde erstellt.
create or replace type "Objektliste" as table of "Objekt";
/
Typ wurde erstellt.
create or replace type "Eigentuemer" is object(
"@besitzer" varchar2(30),
"Objekte" "Objektliste");
/
Typ wurde erstellt.Code example: an object for preparing XML creation
Type "Objekt", created first, represents what will become the innermost XML level. The unusual double quotes cause identifiers to become attributes or children and preserve case-sensitive names. It represents a Data Dictionary object. A user’s object list is represented by type "Objektliste". Finally, an object of type "Eigentuemer" holds the owner name and object list. Examine the declarations to see how aliases control attributes and element names.
A SQL query now converts relational table data into this object structure:
create or replace view object_xml as
select "Eigentuemer"(
initcap(owner),
cast(
multiset(
select "Objekt"(object_type, created, object_id,
object_name, status, last_ddl_time)
from all_objects d
where d.owner = u.owner)
as "Objektliste")) "Objektliste"
from all_objects u
where owner = user
group by owner;
View wurde erstellt.Code example: creating an object-relational view
The statement’s highlight is the combination cast(multiset(...) as "Objektliste"). Read it as: “Take a list (multiset) of "Objekt" instances and convert them (cast) into an instance of type "Objektliste".” I currently restrict the view to the logged-in user ( Scott) to keep data volumes under control. Having encapsulated this complexity in a view, we can simply query it. SQL Developer’s output is rather uninformative (orace.sql.STRUCT@1c1b57 in my case), but SQL*Plus with some formatting reveals the structure:
select *
from object_xml;
Objektliste
---------------------------------------------------------------
Eigentuemer('Scott',
Objektliste(
Objekt('TYPE', '23.05.13', 1360957, 'Objektliste', 'VALID', '23.05.13'),
Objekt('TYPE', '23.05.13', 1360955, 'Objekt', 'VALID', '23.05.13'),
Objekt('TYPE', '23.05.13', 1360960, 'Eigentuemer', 'VALID', '23.05.13'),
Objekt('INDEX', '16.05.13', 1330107, 'PK_EMP', 'VALID', '16.05.13'),
Objekt('TABLE', '16.05.13', 1330104, 'DEPT', 'VALID', '16.05.13'),
Objekt('INDEX', '16.05.13', 1330105, 'PK_DEPT', 'VALID', '16.05.13'),
Objekt('TABLE', '16.05.13', 1330106, 'EMP', 'VALID', '16.05.13'),
Objekt('TABLE', '16.05.13', 1330108, 'BONUS', 'VALID', '16.05.13'),
Objekt('TABLE', '16.05.13', 1330109, 'SALGRADE', 'VALID', '16.05.13'),
Objekt('VIEW', '16.05.13', 1330133, 'EMP_XML', 'VALID', '16.05.13')
)
)Code example: displaying the object type in SQL*Plus
We see nested constructor functions, each returning its data type. We can now imagine XML output after dbms_xmlgen has processed this type:
declare
ctx dbms_xmlgen.ctxHandle;
begin
ctx := dbms_xmlgen.newContext(
'select *
from object_xml');
dbms_xmlgen.setRowTag(ctx, null);
dbms_xmlgen.setRowSetTag(ctx, null);
insert into xml_test_1
values (10, dbms_xmlgen.getXmlType(ctx));
end;
/
PL/SQL-Prozedur erfolgreich abgeschlossen.Code example: generating XML from the object
Here I chose to generate the result as XMLType and insert it into our XML test table. Everything else in the PL/SQL block is familiar, so here is the result:
<Objektliste besitzer="Scott">
<Objekte>
<Objekt art="FUNCTION" erstellungDatum="23.05.2013 10:13:53" id="1360859">
<Name>TEST_FUNC</Name>
<Status>VALID</Status>
<LetzteAenderung>23.05.2013 10:39:01</LetzteAenderung>
</Objekt>
<Objekt art="FUNCTION" erstellungDatum="23.05.2013 10:36:20" id="1360865">
<Name>TEST_FUNC_DET</Name>
<Status>VALID</Status>
<LetzteAenderung>23.05.2013 10:39:01</LetzteAenderung>
</Objekt>
<Objekt>
...
</Objekt>
</Objekte>
</Objektliste>Code example: the result—XML from an object
The result broadly matches SQL/XML output, but required object types and PL/SQL. That would be acceptable if performance clearly demanded it. Unfortunately, it is not that simple. My tests and project experience with 11gR2 suggest that for large instances—perhaps 1 MB as an initial test boundary, depending on hardware—generating XML through dbms_xmlgen is faster and uses fewer resources than SQL/XML or XQuery. For many small instances, common in message-based systems, the reverse holds: SQL/XML/XQuery is faster and lighter. As always, many parameters affect performance. This recommendation only emerged with 11.2; earlier, SQL/XML was almost always slower than the object-oriented approach. Since Oracle deprecated object-based XML generation in 12c, at least function sys_xmlgen, further SQL/XML performance improvements can be expected.
Creating XML from hierarchical queries
The package can also handle hierarchical queries. To my knowledge, SQL/XML alone cannot perform this conversion, though the package uses SQL/XML to calculate the result. This is particularly useful for populating tree structures with XML, such as an HTML TreeView control:
declare
ctx dbms_xmlgen.ctxHandle;
sql_stmt varchar2(32767);
begin
sql_stmt :=
'select level,
xmlelement("Mitarbeiter",
xmlattributes(
initcap(ename) "Name",
initcap(job) "Beruf")) result
from emp
start with mgr is null
connect by prior empno = mgr
order siblings by ename';
ctx := dbms_xmlgen.newContextFromHierarchy(sql_stmt);
dbms_output.put_line(dbms_xmlgen.getXml(ctx));
end;
/
<?xml version="1.0"?>
<Mitarbeiter Name="King" Beruf="President">
<Mitarbeiter Name="Blake" Beruf="Manager">
<Mitarbeiter Name="Allen" Beruf="Salesman"/>
<Mitarbeiter Name="James" Beruf="Clerk"/>
<Mitarbeiter Name="Martin" Beruf="Salesman"/>
<Mitarbeiter Name="Turner" Beruf="Salesman"/>
<Mitarbeiter Name="Ward" Beruf="Salesman"/>
</Mitarbeiter>
<Mitarbeiter Name="Clark" Beruf="Manager">
<Mitarbeiter Name="Miller" Beruf="Clerk"/>
</Mitarbeiter>
<Mitarbeiter Name="Jones" Beruf="Manager">
<Mitarbeiter Name="Ford" Beruf="Analyst">
<Mitarbeiter Name="Smith" Beruf="Clerk"/>
</Mitarbeiter>
<Mitarbeiter Name="Scott" Beruf="Analyst">
<Mitarbeiter Name="Adams" Beruf="Clerk"/>
</Mitarbeiter>
</Mitarbeiter>
</Mitarbeiter>
PL/SQL-Prozedur erfolgreich abgeschlossen.Code example: creating XML from hierarchical queries
Again, as when using package dbms_xmlgen, a context identifies the query environment. Function newContextFromHierarchy in line 15 receives the hierarchical query’s pseudocolumn level and an instance of the XML element to nest. In return, no settings for rowSetTag and rowTag are needed. The result is correctly nested XML with correctly sorted siblings.
Paginating XML queries
Another important feature of package dbms_xmlgen is query pagination with XML output. The task is to convert only rows n through m into XML. Use procedures setMaxRows and setSkipRows. The context preserves the result set, solving consistency during iterative retrieval: further subsets can be returned as XML without rerunning the query. No example is needed since the process matches earlier examples; just set the number and first row with these methods before creating XML. To find how many rows the last call actually processed, use getNumRowsProcessed. If fewer rows were processed than requested, no more remain. Also remember 12c’s new result-limiting capabilities through the row limiting clause (offset and fetch n rows).
SYS_XMLGEN
Let us finish with function sys_xmlgen, which exposes package dbms_xmlgen through SQL and simplifies generating XML from objects. Rather than calling package dbms_xmlgen as in code example “The result—XML from an object”, generate XML directly within SQL using this function:
select sys_xmlgen(x."Objektliste") resultat
from object_xml x
RESULTAT
----------------------------------------------------------------
<?xml version="1.0"?>
<Objektliste besitzer="Scott">
<Objekte>
<Objekt art="FUNCTION" erstellungDatum="23.05.13" id="1360859">
<Name>TEST_FUNC</Name>
<Status>VALID</Status>
<LetzteAenderung>23.05.13</LetzteAenderung>
</Objekt>
<Objekt art="FUNCTION" erstellungDatum="23.05.13" id="1360865">
<Name>TEST_FUNC_DET</Name>
<Status>VALID</Status>
<LetzteAenderung>23.05.13</LetzteAenderung>
</Objekt>
<Objekt>
...
</Objekt>
</Objekte>
</Objektliste>Code example: generating XML from objects in SQL
You may also pass a special XMLFormat object with broadly the same settings as the package parameters. See the online documentation for details; I will not cover them here because this function is deprecated in 12c.
Copyright © Rheinwerk Verlag, Bonn 2014, second edition
You may print the online version for private use.
Otherwise, this chapter from "Oracle PL/SQL: Das umfassende Handbuch" is subject to the same terms as the printed edition: the work and all its parts are protected by copyright. All rights reserved, including reproduction, translation, microfilming, and storage and processing in electronic systems.
Rheinwerk Verlag GmbH, Rheinwerkallee 4, 53227 Bonn, www.rheinwerk-verlag.de, service(at)rheinwerk-verlag.de