XML technologies / Oracle & XML / XML queries / Creating XML instances with SQL/XML
(Excerpt from "Oracle SQL: Das umfassende Handbuch", chapter 17 "XML-Abfragen", by Jürgen Sieben)
The extensions discussed here also belong to the ISO SQL standard, specifically SQL/XML. Essentially, they are simple scalar functions and a few aggregate functions, used like all other such functions in SQL. They all produce a data type supplied with Oracle Database, named XMLType. This is not merely text resembling XML, but an object-oriented type containing both data and methods for working with them. For XMLType, these methods include searching XML with XPath, transforming XML with XSLT files, and other tasks.
A simple example
I would like to demonstrate XML creation step by step. The task is to create an XML instance for each company department containing its employees’ data. First understand that the SQL/XML functions we will use are ordinary scalar and aggregate functions. Syntactically they are equivalent to functions such as lower or sum and can be used the same way, even combined with “normal” scalar functions.
Let us start with a statement that looks rather strange:
select xmlelement("Mitarbeiter") resultat
from dual;
RESULTAT
----------------------------------------------
<Mitarbeiter></Mitarbeiter>Code example: getting started—a rather strange statement
The statement uses scalar function xmlelement and passes a parameter in double quotes. These quotes are mandatory because XML is case-sensitive and we want element names to match our specification exactly. The result is an empty XML element. To the database, even this result is XML rather than text.
The next extension adds attributes to this root element, so I now switch to table emp. We want to represent the hire date and employee number as attributes. To do so, nest within the call to xmlelement as its second parameter a function named xmlattributes. It accepts a list of columns with aliases. Each alias becomes an attribute name and the column value becomes its value. Careful formatting is already essential to track all the parentheses. Nothing is worse than writing pages of SQL and receiving ORA-00907: Rechte Klammer fehlt. Format meticulously and things should go smoothly.
select xmlelement("Mitarbeiter",
xmlattributes(
hiredate "einstellDatum",
empno "id"
)
) resultat
from emp;
RESULTAT
----------------------------------------------------------------
<Mitarbeiter einstellDatum="1980-12-17" id="7369"></Mitarbeiter>
<Mitarbeiter einstellDatum="1981-02-20" id="7499"></Mitarbeiter>
<Mitarbeiter einstellDatum="1981-02-22" id="7521"></Mitarbeiter>
<Mitarbeiter einstellDatum="1981-04-02" id="7566"></Mitarbeiter>
<Mitarbeiter einstellDatum="1981-09-28" id="7654"></Mitarbeiter>
<Mitarbeiter einstellDatum="1981-05-01" id="7698"></Mitarbeiter>
<Mitarbeiter einstellDatum="1981-06-09" id="7782"></Mitarbeiter>
<Mitarbeiter einstellDatum="1987-04-19" id="7788"></Mitarbeiter>
<Mitarbeiter einstellDatum="1981-11-17" id="7839"></Mitarbeiter>
<Mitarbeiter einstellDatum="1981-09-08" id="7844"></Mitarbeiter>
<Mitarbeiter einstellDatum="1987-05-23" id="7876"></Mitarbeiter>
<Mitarbeiter einstellDatum="1981-12-03" id="7900"></Mitarbeiter>
<Mitarbeiter einstellDatum="1981-12-03" id="7902"></Mitarbeiter>
<Mitarbeiter einstellDatum="1982-01-23" id="7934"></Mitarbeiter>
14 Zeilen ausgewählt.Code example: adding attributes
Oracle has now created the attributes. Attributes always belong to the directly enclosing XML element. Next I create child elements. Since these are already leaves in the XML structure and should contain no attributes (their content is simpleType), we can use the aptly named function xmlforest, which, like xmlattributes, creates children from columns and aliases. If your children need their own children or attributes, this approach will not work; instead, call xmlelement to regain all options. I will do that in the next iteration. This next example also uses familiar scalar functions to demonstrate that nesting them works here too:
select xmlelement("Mitarbeiter",
xmlattributes(empno "id",
hiredate "einstellDatum"),
xmlforest(initcap(ename) "Name",
initcap(job) "Beruf",
to_char(sal, '9G990D00L') "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: a refined version with child elements
Oracle evidently knows how to convert a date into XML form, since column HIREDATE is passed as date without a format mask. XML’s standard date format is yyyy-mm-ddThh24:mi:ss. However, since column HIREDATE contains a date rather than a timestamp, the shorter form yyyy-mm-dd, also allowed in XML, was chosen. As you recall, ISO dates contain no time. To preserve the time from a date in XML, explicitly convert it or convert the date column into a timestamp column. Before exploring more options, let us clarify exactly how automatic format conversion works through two sample queries:
select xmlelement("Test", current_timestamp) ts
from dual;
TS
-------------------------------------------------
<Test>2012-03-28T13:34:37.312000+02:00</Test>
select xmlelement("Test", current_date) dt
from dual;
DT
-------------------------------------------------
<Test>2012-03-28</Test>Code example: automatic date conversion
Now it is clearer: in accordance with ISO, a date becomes a short XML date and a timestamp a long one.
But let us continue. Calling these as scalar functions on a table naturally returns a corresponding number of rows. Each now contains a valid instance of XMLType and could therefore call any method defined for that type. Our task, however, was an employee list per department containing all its employees. We still need an aggregate function.
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;Here you see that xmlelement can be nested as a parameter in xmlelement. This 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-12Code example: grouping XML output into one row
Aggregate function xmlagg combines its internal results into a group of XML elements (an XML fragment ) nested in the enclosing element. We now have one row, but not yet the required employee list per department. This final change uses ordinary SQL rather than SQL/XML: simply partition the aggregate function with group by. To clarify the result, I also output the department number as attribute abteilung of the 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: the result—one XML employee list per department
The syntax takes some getting used to, but you will agree that these functions make generating XML from relational data extremely easy. No programming is needed; a simple SQL statement suffices. The same principle creates arbitrarily complex nested XML. Just keep an overview: as queries grow, tracking function calls, their attributes and nesting, especially all the parentheses, is vital.
Scalar or correlated subqueries can produce more deeply nested XML. Such SQL is no longer trivial, though in my experience complex XML rarely needs generating from relational data: most messages have fairly simple internal structures. Another limitation concerns the resulting instance’s size. There is no inherent size limit, since XMLType ultimately is a clob, but computation time and memory use rise exponentially. I can only speculate why; I assume these functions build a DOM tree in memory and add function results as new elements to that DOM tree. Since an in-memory DOM tree can easily occupy ten times the resulting XML file’s size, managing the structure becomes increasingly expensive.
Digression: DOM and SAX
I used the term DOM tree. Briefly, an XML instance is hierarchical, with an internal tree structure. But what we see when viewing XML is not everything a DOM tree contains. First, I forgot to introduce the abbreviation: DOM means Document Object Model represents any XML structure. It distinguishes the root, root element, nodes and leaves, as well as attributes, whitespace, element values and other element types. DOM trees describe all these in great detail in memory, enabling a SQL parser—that is, a program processing XML—to navigate and manipulate the instance.
By contrast, you may hear the term SAX in relation to XML. This is a more dynamic model—or rather a programming strategy. With SAX, XML is read sequentially from beginning to end. The program “listens” and intervenes when something interesting appears. SAX requires only the current node rather than an entire tree in memory, making many XML tasks lighter and less resource-intensive than DOM. DOM, however, is better suited to moving back and forth in the tree.
In practice, I tend to use this technique for XML instances up to about 1 MB. Above that, other approaches are more efficient, especially the database’s object-oriented XML creation functions. They seem to generate XML in one pass from object structures instead of building it node by node through DOM. This approach is harder to implement and less flexible, but considerably faster when performance demands it. I also use it when generating many XML instances quickly, where the individual construction steps become costly. Put simply, I use the approach above while its performance is acceptable and switch to the object-oriented one when necessary.
Overview of other SQL/XML functions
Oracle Database provides several more SQL/XML functions, discussed below.
Other functions for creating XML instances
Most of the following functions are self-explanatory: they create special XML constructs such as processing instructions, comments or prolog information. This group includes:
xmlroot
Creates an XML prolog of the form<?xml version="1.0" standalone="yes"?>. Its syntax is somewhat awkward: the function encloses the entirexmlelementfunction before supplying further parameters. The function’s start and its parameters are therefore far apart:xmlroot(xmlelement(...), version '1.0 ', standalone yes)xmlpi
Creates a processing instruction. This function may appear anywhere in the SQL statement. Its syntax is:xmlpi(name "xml-stylesheet", 'type="text/xsl" href="sample.xslt"')xmlcomment
As its name suggests, inserts a comment into the XML tree. The syntax is simple:xmlcomment('...')xmlconcat
Concatenates XML fragments, much like the SQL functionconcat. Like that function, I have never neededxmlconcateither.xmlcdata
CDATA sections are ignored by the XML parser, but they are not comments. They can, for example, embed Base64-encoded binary data in an XML file. The syntax is:xmlcdata('...')xmlserialize
Creates an XML instance, either a well-formed document or a fragment. Depending on its parameters, it can use a different character encoding, indent whitespace and output the result, for example, asblob. An example is included in the book’s script.
Functions for extracting data from XML instances
SQL/XML defines several data extraction functions. Oracle supports the following:
extractValue
This is Oracle’s replacement for the SQL/XML functionxmlcast, which Oracle does not provide. It expects an XML instance and an XPath expression identifying the node value to extract. The result can then be converted into the target type using appropriate functions (to_*,cast).xmltable
This powerful function converts an XML instance into a relational table using an XPath or XQuery expression. An example follows later.
SQL/XML functions not supported, or only partly supported, by Oracle
You may know other functions that you would like to use in Oracle but that are not implemented. Some have alternatives; others are not supported at all yet. A current list here would be unhelpful: it could change with the next release and be inaccurate for older versions. For questions about standard compatibility, consult Appendix C of the Oracle Database SQL Language Reference, which discusses SQL/XML conformance for your database in detail.
Copyright © Rheinwerk Verlag, Bonn 2013
You may print the online version for private use.
Otherwise, this chapter from "Oracle 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