XML technologies / Oracle & XML / Working with XML / Extracting relational data from XML
(Excerpt from "Oracle PL/SQL: Das umfassende Handbuch", chapter 16 "Arbeiten mit XML", by Jürgen Sieben)
The reverse of XML generation is extracting data from existing XML. Several approaches are available here too:
XQuery
automatic shredding through object-relational tables
manual shredding through Java programming
Extracting relational data with XMLTable
We again begin with the XQuery standard. An English introduction to XQuery integration in Oracle Database appears in the Oracle XML DB Developer’s Guide: “Using XQuery with Oracle XML DB”. For our purposes, it is enough to show how function XMLTable() can unnest an XML instance’s contents.
Digression: XQuery
From version 10g R2, SQL/XML functionality expanded considerably, mainly because many standards only then became mature enough to implement. For extracting data from existing XML instances,XMLTableis useful. Based on XQuery, it joined Oracle’s XML functionality relatively late. It searches existing XML instances like local database resources and converts results into relational structures with simple syntax.
XQuery provides a query language for XML data adopted by the W3C. XQuery queries have structure and power broadly comparable to SQL. Just as SQL assembles subsets of relational data for a task, XQuery extracts corresponding data from XML files. Production XML can be very complex in both the number of structured elements and nesting depth. A language with standardized syntax that extracts subtrees for further processing is therefore very welcome.
XQuery’s core technique consists of queries whose keywords For-Let-Where-Order-By-Return form the acronymFLWOR, pronounced like the English word flower. Such queries run against XML instances and, like SQL on relational tables, filter, calculate, rearrange and output elements. The clauses of aFLWORquery roughly correspond to clauses in aselectstatement, except that the data source is XML and navigation uses XPath expressions. The result is a sequence of XML elements. It need not, and usually will not, be well-formed XML; expect fragments or even scalar values for later processing. This makes XQuery ideal for processing data already stored as XML, though it can theoretically also generate XML from relational data.
Function XMLTable processes the supplied XML instance with an XQuery query and returns the generated data. In the simplest case, the query is an XPath expression, simply pointing to the subtree to retrieve. Let us look at an example. First I create a table from a previously discussed SQL/XML query to serve as our XML source:
create table emp_xml as
select xmlelement("Mitarbeiterliste",
xmlagg(
xmlelement("Mitarbeiter",
xmlattributes(
empno "mitarbeiterId",
hiredate "einstellDatum"),
xmlforest(
initcap(ename) "Name",
initcap(job) "Beruf",
sal "Gehalt",
comm "Boni")
order by ename)
) xml_content
from emp;
Tabelle wurde erstellt.This time I omit grouping by department to produce a somewhat larger XML instance. Notice also the sorting criterion inside xmlagg in line 12, which sorts data before aggregation. Now that we have XML, let us unnest it back into relational data:
select upper(v.ename) ename, upper(v.job) job, v.sal, v.comm
fromemp_xml x,
XMLTable('/Mitarbeiterliste/Mitarbeiter'
passing x.xml_content
columns
empno number path '@mitarbeiterId',
hireadate date path '@einstellDatum',
ename varchar2(20 char) path 'Name',
job varchar2(20 char) path 'Beruf',
sal number path 'Gehalt',
comm number path 'Boni') v;
ENAME JOB SAL COMM
---------- ---------- ------- -------
ADAMS CLERK 1100
ALLEN SALESMAN 1600 300
BLAKE MANAGER 2850
CLARK MANAGER 2450
FORD ANALYST 3000
JAMES CLERK 950
JONES MANAGER 2975
KING PRESIDENT 5000
MARTIN SALESMAN 1250 1400
MILLER CLERK 1300
SMITH CLERK 800
SCOTT ANALYST 3000
TURNER SALESMAN 1500 0
WARD SALESMAN 1250 500
14 Zeilen ausgewählt.Code example: extracting XML with XMLTable
The first clause of XMLTable specifies the XML to extract. Here I used a simple XPath expression; a complete XQuery query would also be possible. The following passing clause specifies the data on which that expression operates. Through outer table alias x I pass column xml_contentXML from table emp_xml into the function, much like a correlated subquery. Everything else refers to the XPath result, here an XML fragment with many Mitarbeiter nodes at the top level. Next we map XML elements to columns and SQL data types. I find the notation using the columns clause and XPath expressions very intuitive. Finally, give the XMLTable function an alias, and access its data like a relational table.
Full XQuery queries provide more elaborate and powerful extraction options, although their results are usually XML instances again. Here is just one representative query, since XQuery is powerful and beyond this book’s scope. Still, I want to give you a visual impression of a FLWOR expression:
select v.*
from emp_xml x,
XMLTable('for $i in /Mitarbeiterliste/Mitarbeiter
where $i/Beruf eq "Salesman"
return $i'
passing x.xml_content
columns
empno number path '@mitarbeiterId',
hireadate date path '@einstellDatum',
ename varchar2(20 char) path 'Name',
job varchar2(20 char) path 'Beruf',
sal number path 'Gehalt',
comm number path 'Boni') v;
EMPNO HIREADAT ENAME JOB SAL COMM
------- ----------- ---------- ---------- ---------- ----------
7499 20.02.81 Allen Salesman 1600 300
7654 28.09.81 Martin Salesman 1250 1400
7844 08.09.81 Turner Salesman 1500 0
7521 22.02.81 Ward Salesman 1250 500Code example: an XQuery statement
As you see, XQuery provides functionality similar to SQL for XML data. For learning XQuery, consider “XQuery – Grundlagen und fortgeschrittene Methoden” by Wolfgang Lehner and Harald Schöning, published by dpunkt. If you know and miss extraction using extract and extractValue, that approach has been deprecated since Oracle 11.2.
Extracting relational data through object orientation
Understanding the details requires background that I can only fully explain under The XML database. Rather than anticipating that section, I will explain the principle here and supply details later.
First register an XML schema in the database. The schema is stored in XML DB and identified to the database through a namespace. Use either the namespace declared in the schema as targetNamespace or its storage path within XML DB. Before registration, annotate the schema with extra attributes from namespace xmlns:xdb="http://xmlns.oracle.com/xdb". These attributes help map XML elements to object or SQL data types. For example, a subtree can be stored as an instance of type OBJECT_T in the database, or element Mitarbeiter can be stored in a varchar2(30) field. This mapping defines the rules for representing XML in an object-relational model.
While registering the schema, package dbms_xmlschema can also generate object-relational tables, object types and even JavaBeans for accessing them. The XML schema instance thus defines the complete database storage structure, which registration creates immediately.
Next, execute an insert statement to insert an XML instance into that table. Oracle converts it into the corresponding object and inserts it into the appropriate object-relational tables. The data then becomes directly accessible through select statements on the object-relational import table.
Inserting this way takes longer than simply writing data to a CLOB column, and also longer than writing them to a BinaryXML column. Subsequent access is much faster than with a CLOB column, but not much faster than accessing an XML instance stored as BinaryXML. This property of BinaryXML has therefore reduced this approach’s appeal. An alternative would be an object-relational view over a BinaryXML column, probably with similar access times.
Without going into depth, I would still like to give some reasons why I dislike object-relational storage for large data volumes:
Nested information is accessible only through its containing object. For example, order items can only be accessed through the order. Directly querying the nested table to count orders per product is therefore impossible. This contradicts my expectation of unrestricted access to all data in a relational database.
update statements against such a table are costly for the same reason: each order item is treated as residing in its own table, though it does not actually do so. This channeling of access bothers me too.
Oracle ultimately creates a relational model with special restrictions. I find it easier to create the required tables myself, retaining control over their structures and treating data modeling as a deliberate design process rather than an automatic by-product.
Storage takes considerable space because data references form a network of conventional relational tables. The key is an OID (object ID), 16 bytes wide and therefore probably larger than most ordinary keys. All linked object instances use such keys.
Let us look at the last point, because the function sys_op_guid() generates such an OID:
select sys_op_guid() oid, dump(sys_op_guid()) dump_oid
from dual;
OID
--------------------------------
DUMP_OID
--------------------------------------------------------------
CDAAD9F162FF4372961E0DDF6DD66A2B
Typ=23 Len=16: 32,163,204,141,183,221,68,78,130,28,254,63,103,136,205,134Code example: displaying an OID with sys_op_guid
Extracting relational data through Java programming
I can only outline the approach here: read the XML instance sequentially once, raising an event for each element. Analyze those events and use mapping tables to distribute them to one or more prepared statements (SQL statements configured through parameters), each representing an insert into a target table. Once a prepared statement has all its parameters, send it to insert the data.
This basic approach leaves room for many optimizations. Minimize roundtrips to the database server by sending statements in batches and creatively supplying primary-key values. Also use deferrable constraints to insert children before parents. Finally, all Java code can run inside the database—not Oracle XE, whose kernel lacks a Java Virtual Machine (JVM)—further reducing network latency. Access then uses a PL/SQL wrapper method.
This approach achieves very high performance: it is extremely fast and uses consistently little memory because no DOM tree is created. It fully exploits available mechanisms: database transactions, validation through the SAX parser and Java-driver optimizations. Programming is fundamentally the same regardless of the XML inputs or target tables. A code generator can therefore automate much of it, even making the XML-to-column mapping configurable from external sources and generating the corresponding mappers automatically.
Despite these benefits, Java programming is naturally more demanding and less maintainable than, for example, XQuery. This approach is strongest with XML of low to moderate complexity, as is common in message-based systems.
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