XML technologies / Oracle & XML / XML queries / Working with XQuery
(Excerpt from "Oracle SQL: Das umfassende Handbuch", chapter 17 "XML-Abfragen", by Jürgen Sieben)
If you know XQuery well, you may accuse me of discussing colors like a color-blind person. I admit my knowledge is not especially deep. I use the technology rather superficially, which I accept because no problem has yet forced me to study it in depth.
XQuery, even I know, is something of a counterpart to SQL. SQL is optimized for structured information in tables, whereas XQuery is optimized for semistructured data in a hierarchy. It is a complete, sequence-oriented query language: Everything in XQuery is a sequence of elements or scalar values, somewhat like a list or array, except that values may repeat and lists may be ordered.
The query language is based on a FLWOR expression, pronounced like the English word flower. This acronym stands for for – where – let – order by – return, the keywords of a typical XQuery query. In essence, for and let correspond to from, where and order by correspond to their SQL counterparts, and return corresponds to select. Thus the languages are semantically close, although their keywords appear in a different order.
Nevertheless, XQuery is fundamentally different from SQL. Oracle Database supports XQuery 1.0 as an alternative query language, as well as XPath 2.0, part of the XQuery specification. There is also a SQL*Plus command, XQUERY, which switches SQL*Plus into XQuery mode. The officially defined SQL/XQuery interface, part of SQL/XML, is provided by xmlquery, xmltable, xmlexists and xmlcast. I want to explain these functions rather than XQuery’s internals, which I must admit I largely still need to learn. I can only show basic queries sufficient to demonstrate the functions. I am far from mastering the advanced possibilities for replacing XSLT and creating XML instances. This section is therefore no substitute for a specialized XQuery book.
The XMLQUERY function
Let us begin with xmlquery, used to generate XML from relational data or extract XML from other XML data. It belongs to SQL/XML but does not support every use defined by the standard. In particular, it returns only XMLType instances, not sequences, the building blocks of XQuery queries. Thus, xmlquery has mandatory clauses with no alternative because the alternatives are unsupported. Unusually, I will show its basic structure before building an example. Its first parameter is an XQuery expression, which can be as simple as an XPath expression or use the full range of a FLWOR statement. Next, we may optionally supply a context, as is often needed: the raw data on which the expression operates. In the simplest case, this is a table containing an XML instance. Relational columns and scalar data are also accepted, but not object-relational structures, which must first be converted to XML using SQL/XML. Finally, the mandatory clause is returning content. Let us leave it at that for now and look at the overview:
xmlquery(<XQuery-Ausdruck>
passing <XML-Instanz>
returning content)Code example: basic structure of XMLQUERY
Start with a very simple example, passing an XPath expression rather than a FLWOR query and using our familiar XML column as context:
select xmlquery(
'/Mitarbeiterliste/Mitarbeiter'
passing liste
returning content) ergebnis
from dept_emp_xml;
ERGEBNIS
-------------------------------------------------------------
<Mitarbeiter einstellDatum="1981-06-09" id="7782"><Name>Clark...
<Mitarbeiter einstellDatum="1980-12-17" id="7369"><Name>Smith...
<Mitarbeiter einstellDatum="1981-02-20" id="7499"><Name>Allen...Code example: a first use of xmlquery
The XPath expression simply removes root element Mitarbeiterliste from the employees and returns them as an XML fragment. This barely reveals the function’s power. Next, we omit the passing clause and obtain data for XQuery directly from the database using fn:collection, whose unusual syntax requests database rows as XML: oradb:/SCOTT/EMP. It means: view the database as one huge XML instance (oradb), navigate to node SCOTT and then node EMP. Oracle XML DB provides this standardized XML view of relational data. Suppose we want to represent table SCOTT.EMP this way. In the standard representation, each row becomes an element named ROW. Each column produces a child named after that column and containing its value for the row. The XML structure is:
<SCOTT>
<EMP>
<ROW>
<EMPNO>7369</EMPNO>
<ENAME>SMITH</ENAME>
<JOB>CLERK</JOB>
<MGR>7902</MGR>
<HIREDATE>1980-12-17</HIREDATE>
<SAL>800</SAL>
<DEPTNO>20</DEPTNO>
</ROW>
<ROW> ... </ROW>
</EMP>
<DEPT>...</DEPT>
</SCOTT>Code example: basic XML format of a table accessed through oradb
SMITH is not a SALESMAN and is therefore not entitled to commission, so child element COMM is absent. Generally, null values are omitted. Since our FLWOR query accesses table EMP directly, we do not need clause passing. The query is:
select xmlquery(
'for $emp in fn:collection("oradb:/SCOTT/EMP")
where $emp/ROW/SAL >= 3000
return <Mitarbeiter>
<Name>{$emp/ROW/ENAME/text()}</Name>
<Gehalt>{$emp/ROW/SAL/text()}</Gehalt>
</Mitarbeiter>'
returning content) ergebnis
from dual;
ERGEBNIS
----------------------------------------------------------------
<Mitarbeiter>
<Name>SCOTT</Name>
<Gehalt>3000</Gehalt>
</Mitarbeiter>
<Mitarbeiter>
<Name>KING</Name>
<Gehalt>5000</Gehalt>
</Mitarbeiter>
<Mitarbeiter>
<Name>FORD</Name>
<Gehalt>3000</Gehalt>
</Mitarbeiter>Code example: querying with a FLWOR expression
After some formatting, we see that this function generated XML from relational data. We create the structure by writing it explicitly. The result really is XML, not merely text resembling it. This technique even supports joins between tables:
select xmlquery(
'for $emp in fn:collection("oradb:/SCOTT/EMP"),
$dept in fn:collection("oradb:/SCOTT/DEPT")
where $emp/ROW/DEPTNO = $dept/ROW/DEPTNO
and $emp/ROW/SAL >= 3000
return <Mitarbeiter>
<Name>{$emp/ROW/ENAME/text()}</Name>
<Gehalt>{$emp/ROW/SAL/text()}</Gehalt>
<Abteilung>{$dept/ROW/DNAME/text()}</Abteilung>
</Mitarbeiter>'
returning content) ergebnis
from dual;
ERGEBNIS
----------------------------------------------------------------
<Mitarbeiter>
<Name>KING</Name>
<Gehalt>5000</Gehalt>
<Abteilung>ACCOUNTING</Abteilung>
</Mitarbeiter>
<Mitarbeiter>
<Name>FORD</Name>
<Gehalt>3000</Gehalt>
<Abteilung>RESEARCH</Abteilung>
</Mitarbeiter>
<Mitarbeiter>
<Name>SCOTT</Name>
<Gehalt>3000</Gehalt>
<Abteilung>RESEARCH</Abteilung>
</Mitarbeiter>Code example: adding joins
Naturally, each query uses table DUAL, since XQuery accesses the actual tables. FLWOR expressions can be nested to represent 1:n relationships between elements. At the position in the output tree (the return clause) where repeated children should appear, place the FLWOR expression for those children. This is not an XQuery book, so consult either the Oracle XML DB Developers Guide, chapter 5, “Using XQuery with Oracle XML DB”, or a specialized XQuery book.
The XMLTABLE function
The reverse of xmlquery is provided by xmltable. It intuitively unnests XML to recover relational data. Again, a simple example will suffice, although the full expressive power of XQuery is available. I will start with an overview of its structure:
First, an optional parameter declares the instance’s namespaces, allowing the function to use their elements. Next come the XQuery expression and an optional passing clause, as before. The key feature follows: in the columns clause, define which expression maps to which data type and column name. Mapping XML elements to a relational table becomes quite intuitive. Here is the overview:
xmltable(
xmlnamespaces (<Namensraum-Deklaration>),
<xQuery-Ausdruck>
passing <XML-Instanz>
columns <Spaltenmapping>)Code example: overview of xmltable
Naturally, the function belongs in the where clause of a SQL query, since it returns a relational table.
For a slightly more complex example, I will also use an XML namespace to demonstrate that case. The input is an XML file published daily by the European Central Bank containing exchange rates for important currencies against the euro. It is freely available at "http://www.ecb.europa.eu/stats/eurofxref/eurofxref-daily.xml" and contains two namespaces: one for the envelope and one for the European Central Bank. Its general structure is:
<gesmes:Envelope xmlns:gesmes="http://www.gesmes.org/xml/2002-08-01" xmlns="http://www.ecb.int/vocabulary/2002-08-01/eurofxref">
<gesmes:subject>Reference rates</gesmes:subject>
<gesmes:Sender>
<gesmes:name>European Central Bank</gesmes:name>
</gesmes:Sender>
<Cube>
<Cube time="2012-03-29">
<Cube currency="USD" rate="1.3272"/>
<Cube currency="JPY" rate="109.21"/>
<Cube currency="BGN" rate="1.9558"/>
<Cube currency="CZK" rate="24.778"/>
<Cube currency="DKK" rate="7.4372"/>
<Cube currency="GBP" rate="0.83580"/>
...
<Cube currency="THB" rate="40.971"/>
<Cube currency="ZAR" rate="10.2562"/>
</Cube>
</Cube>
</gesmes:Envelope>Code example: an XML instance with namespaces
What follows may seem like magic: I will fetch the current XML file from the ECB within the SQL query and evaluate it directly. In database version 11, an ACL must grant access to this online resource. The book’s script shows how to configure this for user SCOTT. This administration topic need not concern us here. With that configured, a function lets us access an http resource directly from SQL, as follows:
select httpUriType('http://www.ecb.europa.eu/stats/eurofxref/eurofxref-daily.xml').getXml() datei
from dual;
DATEI
----------------------------------------------------------------
<?xml version="1.0" encoding="WINDOWS-1252"?>
<gesmes:Envelope> ...</gesmes:Envelope>Code example: accessing an online resource directly from SQL
This is rather cool. The object-oriented type httpURIType takes a URL and retrieves the resource. Its built-in function getXml() then reads the file as XMLType. We can now extend the query to return only a table of exchange rates. To keep the example manageable, I shortened the namespace identifiers. I also ignored the gesmes namespace, since the envelope elements are irrelevant to the output.
select k.currency, k.rate
from (select httpUriType(
'http://www.ecb.....xml').getXml() msg
from dual) ezb,
xmltable(
xmlnamespaces(
default 'http://www.ecb..../eurofxref'),
'//Cube[@currency]'
passing ezb.msg
columns
currency char(3) path '@currency',
rate number path
'fn:translate(@rate, ".", ",")'
) k;
CURRENCY RATE
-------- -------
USD 1,3272
JPY 109,21
BGN 1,9558
...
33 Zeilen ausgewählt.Code example: extracting data from an online XML resource
Let us examine the parts. Lines 2–4 contain the inner view that reads the ECB resource. It is made available as ezb.msg. The xmltable function receives this message in line 9 through the passing clause. I define the ECB’s default namespace so its elements are visible, and ignore namespace gesmes by using XPath expression // to search the entire document for Cube elements. Only those with a currency attribute interest me, as the XPath expression in line 8 specifies. The columns clause in lines 10–13 maps elements to the resulting table’s columns. Simply specify each column’s name and data type and an XPath expression relative to the XQuery result. One small catch: numeric conversion is not straightforward. Either set parameter nls_territory to AMERICA or replace the attribute’s dot with a comma, since conversion uses the locale’s decimal separator by default. I chose a fn:translate function to replace dots with commas.
XML with namespaces from SQL is quite demanding. You may feel such queries belong in the sadomasochism scene. But much depends on familiarity. The syntax is unusual and sometimes unforgiving about rules, yet highly effective. Such queries are not for beginners, but they can spare experts substantial programming and achieve powerful results—provided they learn XQuery’s concepts.
The XMLEXISTS function
Let us relax with a simpler function, xmlexists, which checks whether an element exists in an XML instance. It accepts XQuery queries, including simple XPath expressions, making it useful for quick lookups and searches. After the previous query, its syntax will seem familiar and easy. I again use the XML instances in table dept_emp_xml:
select liste
from dept_emp_xml
where xmlexists(
'/Mitarbeiterliste/Mitarbeiter[Name = "King"]'
passing liste);
LISTE
------------------------------------------------------------
<Mitarbeiterliste abteilung="10">
<Mitarbeiter einstellDatum="1981-06-09" id="7782">
<Name>Clark</Name>
<Beruf>Manager</Beruf>
<Gehalt>2.450,00€</Gehalt>
</Mitarbeiter>
<Mitarbeiter einstellDatum="1982-01-23" id="7934">
<Name>Müller</Name>
<Beruf>Clerk</Beruf>
<Gehalt>1.300,00€</Gehalt>
</Mitarbeiter>
<Mitarbeiter einstellDatum="1981-11-17" id="7839">
<Name>King</Name>
<Beruf>PRÄSIDENT</Beruf>
<Gehalt>5.000,00€</Gehalt>
</Mitarbeiter>
</Mitarbeiterliste>Code example: filtering with xmlexists
The XMLCAST function
You have briefly seen this function in action. Its use is as straightforward as xmlexists. Pass an expression of any kind, including an XQuery query, and interpret it as a scalar data type. Some standard SQL/XML types are not allowed, such as XMLType. You cannot supply a format mask. If one is needed, prepare the expression so that standard conversion succeeds. I believe this seriously limits the function’s power. Here is another example:
select xmlcast(
xmlquery(
'for $e in //Mitarbeiter
where $e/Name = "Scott"
return
fn:translate($e/Gehalt, ",.€", ",")'
passing liste
returning content) as number) sal
from dept_emp_xml
where xmlexists('/Mitarbeiterliste/Mitarbeiter[Name = "Scott"]'
passing liste);
SAL
----------
3000Code example: using xmlcast
Here I combined everything: xmlcast, xmlquery and xmlexists. The query itself is fairly understandable, but reproducing it may cause problems. Pitfalls include:
the values of the parameters
NLS_TERRITORY, as well asNLS_NUMERIC_CHARACTERSthe database’s character encoding, regarding the euro sign
Such problems can really try your patience …
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