XML technologies / Oracle & XML / XML queries / Extracting data from XML instances with SQL/XML
(Excerpt from "Oracle SQL: Das umfassende Handbuch", chapter 17 "XML-Abfragen", by Jürgen Sieben)
Recovering relational data from XML reverses XML generation. This section covers functions around extract. An alternative is xmltable, discussed with XQuery because it uses that technology.
Extraction requires undoing an aggregate operation. Recall that we created Mitarbeiterliste with xmlagg, an aggregate nesting multiple XML instances in a parent element. A simple group by grouped them by department. We must now undo that grouping with xmlsequence. The function xmlsequence expects an XML fragment whose roots should be treated as separate instances, returning one instance per child. The fragment itself comes from extract, which extracts a fragment identified by an XPath from an XML instance. You already know extract from date operations (extract (year from sysdate)), but here its syntax resembles other XML functions. Parameters are the instance, the XPath expression and optional namespace for the function.
Next comes familiar SQL magic: use table to interpret individual rows from xmlsequence as table rows. These operations must be explained together because SQL performs them in one step, not individually.
Let us unnest the XML instance:
select v.*
from dept_emp_xml x,
table(
xmlsequence(
extract(x.liste, '//Mitarbeiter'))) v
where deptno = 10;
COLUMN_VALUE
-----------------------------------------------------
<Mitarbeiter einstellDatum="1981-06-09" id="7782"><Na...
<Mitarbeiter einstellDatum="1982-01-23" id="7934"><Na...
<Mitarbeiter einstellDatum="1981-11-17" id="7839"><Na...
3 Zeilen ausgewählt
Code example: unnesting the XML instance
We again obtain three rows, one per employee, because I restricted the query to department 10. Without this restriction, all three employee lists unnest into 14 rows. As before, table returns a column named column_value, which appears again here. I call the unnested table v so we can continue working with these rows.
Next, we read the information we need from v.column_value with extract or extractValue. XML is only formatted text, so the returned data type is varchar2. To restore the original data types, conversions are necessary. First a simple example, then the full query: extract the employee name from each row.
select extractValue(v.column_value, '//Name') ename
from dept_emp_xml x,
table(
xmlsequence(
extract(x.liste, '//Mitarbeiter'))) v;
ENAME
---------
Clark
Miller
King
Smith
Ford
Adams
Scott
Jones
Allen
James
Turner
Blake
Martin
Ward
14 Zeilen ausgewählt.
Code example: extracting the employee name
Extraction through extractValue (returning the element’s value, not the whole element) must receive the column COLUMN_VALUE. The XPath refers to its root Mitarbeiter and should strictly be /Mitarbeiter/Name. Wrapping the expression in upper makes the names uppercase again. Here is the complete extraction query:
select upper(
extractValue(
v.column_value, '//Name')) ename,
upper(
extractValue(
v.column_value, '//Beruf')) job,
to_date(
extractValue(
v.column_value,
'/Mitarbeiter/@einstellDatum'),
'yyyy-mm-dd') hiredate,
to_number(
extractValue(
v.column_value, '//Gehalt'),
'999G990D00L') sal,
x.deptno
from dept_emp_xml x,
table(
xmlsequence(
extract(x.liste, '//Mitarbeiter'))) v;
ENAME JOB HIREDATE SAL DEPTNO
---------- ---------- --------- --------- ----------
CLARK MANAGER 09.06.81 2450 10
MILLER CLERK 23.01.82 1300 10
KING PRÄSIDENT 17.11.81 5000 10
SMITH CLERK 17.12.80 800 20
FORD ANALYST 03.12.81 3000 20
ADAMS CLERK 23.05.87 1100 20
SCOTT ANALYST 19.04.87 3000 20
JONES MANAGER 02.04.81 2975 20
ALLEN SALESMAN 20.02.81 1600 30
JAMES CLERK 03.12.81 950 30
TURNER SALESMAN 08.09.81 1500 30
BLAKE MANAGER 01.05.81 2850 30
MARTIN SALESMAN 28.09.81 1250 30
WARD SALESMAN 22.02.81 1250 30
14 Zeilen ausgewählt.Code example: unnesting and converting data from XML instances
Appearance matters less here; copy and paste at least eases the work. A cleaner approach uses xmltable, discussed with XQuery. Such queries can also be stored in database views. If XML were loaded into an import table, a simple statement such as
insert into target
select *
from my_new_view;could transfer the extracted data into relational tables. This example is deliberately simple for teaching purposes—or is that someone muttering “laziness”? Deeper XML requires further calls to table on partially unnested fragments. It becomes complex, beyond what I want to demonstrate in a SQL book, but the principle stays the same.
Another data-type conversion approach uses SQL/XML, specifically xmlcast to convert an XML element into a SQL type. It works, though not always well. In the query above, replace to_date with this expression:
xmlcast(
extract(v.column_value, '/Mitarbeiter/@einstellDatum')
as date)That is the limit, however: other columns still need upper, and the salary format is not recognized. There is no way to explain that format to the function, so it is useful only with clean standard data formats. Then xmlcast can also produce date, timestamp, number and so on. For extracting clob or blob explicitly from XML, Oracle no longer recommends XMLType.GetClob() but the familiar SQL/XML function xmlserialize instead.
A note on locale-specific XML
When converting XML numbers tonumber, remember XML requires a decimal point. Converting tonumberwithout a format mask in, for example, a German-language session causes an error: the database expects a comma that the XML does not supply. Here is a demonstration:
select extract(
xmltype(
'<Foo>3.15</Foo>'),
'/Foo/text()').getNumberVal() zahl
from dual;
'/Foo/text()').getNumberVal() zahl
*
FEHLER in Zeile 4:
ORA-01722: Ungültige Zahl
ORA-06512:
in "SYS.XMLTYPE", Zeile 181XML numbers must use a decimal point; otherwise they are not valid XML numbers and the parser rejects them. Ideally, local separators would not affect conversion. I consider this a bug.
While I am complaining, why doesXMLTypehave nogetDateVal()function? A defined XML Schema standard exists for this too, so implementation should be possible. Perhaps in the next release...
Some queries were simplified by keeping a separate DEPTNO column in the table. Alternatively, select XML instances through a node test. This node test can use extractValue, though this is dated and newer functions and operators, especially xmlexists, do it better:
select liste
from dept_emp_xml
where extractValue(
liste,
'//Mitarbeiter[Name="Scott"]/Name')
= 'Scott';
LISTE
----------------------------------------------------
<Mitarbeiterliste abteilung="20">
<Mitarbeiter einstellDatum="1980-12-17" id="7369">
<Name>Smith</Name>
<Beruf>Clerk</Beruf>
<Gehalt>800,00€</Gehalt>
</Mitarbeiter>
<Mitarbeiter einstellDatum="1981-12-03" id="7902">
<Name>Ford</Name>
<Beruf>Analyst</Beruf>
<Gehalt>3.000,00€</Gehalt>
</Mitarbeiter>
<Mitarbeiter einstellDatum="1987-05-23" id="7876">
<Name>Adams</Name>
<Beruf>Clerk</Beruf>
<Gehalt>1.100,00€</Gehalt>
</Mitarbeiter>
<Mitarbeiter einstellDatum="1987-04-19" id="7788">
<Name>Scott</Name>
<Beruf>Analyst</Beruf>
<Gehalt>3.000,00€</Gehalt>
</Mitarbeiter>
<Mitarbeiter einstellDatum="1981-04-02" id="7566">
<Name>Jones</Name>
<Beruf>Manager</Beruf>
<Gehalt>2.975,00€</Gehalt>
</Mitarbeiter>
</Mitarbeiterliste>Code example: filtering XML instances with extractValue
This is mainly illustrative; xmlexists is better suited, but belongs to XQuery’s approach and syntax and will be discussed there. If you recall existsNode or have seen it in a query, note that since 11g R2 it is deprecated and should likewise be replaced by xmlexists. Since that release, the same status applies to extract and extractValue, used in this section. Where possible, replace them with the new SQL/XML functions xmlquery and xmlcast, covered next. I still use the older functions because they remain widespread and are required before Oracle 11g (xmlcast exists only from version 11).
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
back to top