XML technologies / Oracle & XML / Working with XML / Processing XML with PL/SQL
(Excerpt from "Oracle PL/SQL: Das umfassende Handbuch", chapter 16 "Arbeiten mit XML", by Jürgen Sieben)
After surveying ways to generate XML, we now turn to working with existing XML data. Again, several approaches are available:
We have briefly examined the first two. Yet books and projects often favor DOM interaction, perhaps because it is common in the Java world or possible with built-in PL/SQL tools. Usually unnecessary in the database, I find it complicated. SQL/XML’s updateXML statement can create, delete or add specific subtrees down to a single attribute value without recreating the entire XML instance (from 12c: XQuery). Many changes, especially complex ones, are much easier with XSLT. People often say DOM manipulation feels more familiar, since they would first have to learn XQuery or XSLT. If you perform such transformations often, however, learning them is by far the most elegant approach.
Programming with the DOM tree
XML processing requires some fundamentals. Understanding DOM’s programming model is essential in PL/SQL, while namespaces complicate these structures further. This section explains these concepts and introduces important Oracle XML programming tools.
Digression: the DOM tree and the SAX approach
XML instance programming is based on the DOM tree. This specification defines precisely how XML must be represented in memory for parsers to process it. If I suggested DOM was a root cause of slow XML processing, that is only partly true. It does consume substantial memory: every tiny piece of XML, even whitespace—spaces, tabs and paragraph breaks used for formatting—has its own DOM node. Conversely, DOM is ideal when frequent random access across the document is needed. In my experience, that is rare in message-based systems. The XML community therefore sought an alternative early on, producing the Simple API for XML (SAX), which reads XML sequentially once instead of building DOM, reporting each occurrence—an element, attribute and so on—as an event to the caller. Event handlers catch and process these events directly, rather like triggers. Advantage: No complete in-memory representation is needed, saving resources. Disadvantage: Random element access requires rereading the file repeatedly, usually at much greater cost than DOM. Worse, this approach is unavailable in PL/SQL, which has no events—apart from triggers fired from SQL, which PL/SQL can use but cannot itself generate.
Working with DOM mainly uses the supplied PL/SQL packages, examined next. Navigate the DOM tree either with XPath or by moving through it with methods, like navigating a filesystem from a node to its child or parent element. XML tree navigation is particularly error-prone and will probably cause most of your problems.
Digression: namespaces
XML also allows elements to be bound to a namespace. Namespaces entail a steep learning curve for beginners, especially without experience of similar concepts in Java. Compare a namespace to an Oracle schema: administrators can see a table registered in schema A but must prefix it with A. XML works similarly: an element reference must specify its namespace. Without one, the default namespace is normally used. Otherwise, every search and navigation must use the element’s namespace. PL/SQL supports namespace-aware operations, but they add confusion for beginners.
The Oracle parser
PL/SQL packages expose an interface to Oracle’s XML parser and its main functions. As discussed, its SAX interface is unavailable because PL/SQL has no events. Oracle also provides the XML parser as a separate download for use from Java, for example. It parses XML, validates against DTD and XSD, and transforms with XSLT. It cannot process XSL-FO, like most parsers. That requires additional parsers such as Apache FOP or AntennaHouse’s renderer, or external tools such as Oracle’s BI Publisher. Oracle XML Parser is therefore always the programming basis, even when accessed through PL/SQL packages.
The XML packages
XML processing changes considerably between database versions. Version 9.2 first provided a stable package set, greatly extended in 10g and changed again in 11g. The trend is native kernel integration, offering C’s significant performance advantages over the original Java implementation, alongside much broader functionality. I must therefore focus on one version: 11g. More than elsewhere, consult your own version’s documentation when programming XML. Fortunately, detailed documentation is available, and this overview should help you get started. One source is the XML development document, XML DB Developer’s Guide, covering the parser’s PL/SQL interface and development with XML Database (XDB), examined under The XML database. Further information appears in the PL/SQL Packages and Types Reference, documenting all packages including XML. Most relevant package names contain XML and are easy to identify. Let us examine them.
dbms_xmlparser, dbms_xslprocessor and dbms_xmldom
These packages form the core XML integration interface to Oracle XML Parser and XML documents. They follow W3C’s DOM programming model, comprehensive but not always intuitive. This overview is mainly for projects needing DOM internals. I cannot readily recommend these packages for practical XML work: learning DOM and packages with many partly overlapping methods, such as dbms_xmldom, takes time, and they pursue XML’s maximum theoretical programming capabilities. The paradigm resembles object-oriented Java or C# more than PL/SQL, with many parameters and successive function calls required for trivial tasks.
dbms_xmlparser reads XML documents into a DOM tree and controls validation. After parsing, package dbms_xmldom can inspect and modify every detail, or package dbms_xslprocessor can transform it. Package dbms_xmldom is among Oracle’s most complex, if only by its method count. A complete presentation is therefore impossible here. Understanding the basics must suffice; consult the documents above or a more advanced book for details.
Let us illustrate the basic approach. First convert a string into DOM with dbms_xmlparser, then extend it in a second example using package dbms_xmldom:
set serveroutput on
declare
l_char_doc varchar2(2000);
l_dom_doc dbms_xmldom.domDocument;
l_dom_node dbms_xmldom.domNode;
l_parser dbms_xmlparser.parser;
l_buffer varchar2(2000);
begin
l_char_doc :=
'<Mitarbeiter><Name>King</Name></Mitarbeiter>';
-- l_parser instanziieren und vorbereiten
l_parser := dbms_xmlparser.newParser;
-- Zeichenkette parsen und DOM erzeugen
dbms_xmlparser.parseBuffer(l_parser, l_char_doc);
l_dom_doc := dbms_xmlparser.getDocument(l_parser);
-- Einzelnes Element aus dem Dokument lesen
l_dom_node:= dbms_xmldom.makeNode(l_dom_doc);
-- Element ausgeben
dbms_xmldom.writeToBuffer(l_dom_node, l_buffer);
dbms_output.put_line(l_buffer);
-- Aufräumen
dbms_xmldom.freeDocument(l_dom_doc);
dbms_xmlparser.freeParser(l_parser);
end;
/
<Mitarbeiter>
<Name>King</Name>
</Mitarbeiter>
PL/SQL-Prozedur erfolgreich abgeschlossen.Code example: creating an XML instance with dbms_xmldom
The output shows that our original string is now XML and can be formatted accordingly. This is cumbersome compared with calling an XMLType constructor. We gain finer control, however, over validation while reading, warnings and whitespace handling. Creating a parser in line 12 before using it may look unusual. This is typical of object orientation, like initializing a temporary LOB or collection. In line 14, pass the string to that parser. Configure parsing options before this call. The parsed instance now resides inside the parser. The next call to dbms_xmlparser.getDocument() in line 15 copies the internal document to variable dom_doc for further processing. Variable dom_doc has type dbms_xmldom.domDocument and represents the whole document: in XML terms, the root with all its contents. Technically, the document node specializes the general node type domNode. Since procedure writeToBuffer expects a general domNode as input, first convert the root node to this general node, in line 17. Finally, line 19 outputs that domNode as a string. As I said, many tiny steps …
Release resources with the appropriate package methods when finished, especially if the parser is declared in a package and could survive an entire session. After parsing, package dbms_xmldom takes control and performs the actual XML work. The next example adds another node. To shorten the still lengthy code, I replace dbms_xmlparser with data type XMLType and its constructor to create the XML instance:
declare
l_xml_doc xmlType;
l_dom_doc dbms_xmldom.domDocument;
l_root dbms_xmldom.domNode;
l_root_node dbms_xmldom.domNode;
l_out_buffer varchar2(2000);
procedure setXmlHeader(
p_version_string in varchar2,
p_encoding in varchar2)
as
begin
dbms_xmldom.setVersion(l_dom_doc, p_version_string);
dbms_xmldom.setCharset(l_dom_doc, p_encoding);
end setXmlHeader;
function getChildNode(
p_element_name in varchar2,
p_position in naturaln)
return dbms_xmldom.domNode
as
nodelist dbms_xmldom.domNodeList;
begin
nodelist := dbms_xmldom.getElementsByTagName(
l_dom_doc, p_element_name);
return dbms_xmldom.item(nodelist, p_position);
end getChildNode;
procedure appendChildUnder(
p_parent_node in out dbms_xmldom.domNode,
p_child_name in varchar2,
p_child_value in varchar2)
as
l_element dbms_xmldom.domElement;
l_node dbms_xmldom.domNode;
l_text dbms_xmldom.domText;
begin
l_element := dbms_xmldom.createElement(
l_dom_doc, p_child_name);
l_node := dbms_xmldom.makeNode(l_element);
l_text := dbms_xmldom.createTextNode(
l_dom_doc, p_child_value);
p_parent_node := dbms_xmldom.appendChild(
p_parent_node, l_node);
p_parent_node := dbms_xmldom.appendChild(
l_node, dbms_xmldom.makeNode(l_text));
end appendChildUnder;
begin
-- Erzeuge XML und daraus den DOM-Baum
l_xml_doc :=
xmltype('<Mitarbeiter><Name>King</Name></Mitarbeiter>');
l_dom_doc := dbms_xmldom.newDomDocument(l_xml_doc);
l_root := dbms_xmldom.makeNode(l_dom_doc);
l_root_node := getChildNode('Mitarbeiter', 0);
-- Bearbeite den DOM-Baum
setXmlHeader('1.0', 'ISO-8859-1');
-- Erzeuge neues Element
appendChildUnder(l_root_node, 'Beruf', 'President');
dbms_xmldom.writetobuffer(l_root, l_out_buffer);
dbms_output.put_line(l_out_buffer);
dbms_xmldom.freedocument(l_dom_doc);
end;
/
<?xml version="1.0"?>
<Mitarbeiter>
<Name>King</Name>
<Beruf>President</Beruf>
</Mitarbeiter>
PL/SQL-Prozedur erfolgreich abgeschlossen.Code example: W3C-compliant programming in PL/SQL
Quite simple, is it not? Remember, most of this complexity comes from DOM, not PL/SQL. Java and other languages have simpler interfaces hiding it behind helpers. PL/SQL supplies no such interface, though SQL/XML partly fills that role. If you frequently work at this DOM level, create a package of useful helpers. Let me explain what happens so the example is understandable.
Read the code from bottom to top, starting with the main program at line 49. A constructor creates the XML instance to extend. From it I successively obtain DOM (line 53), the root node (line 54, not the root element!) and the root element (line 55). Leave the helpers aside for now and get the overview.
Next I set information such as version and character encoding, then create a new child beneath the root element. In this example, that element is named Mitarbeiter and currently has only one child, Name. Now a new element, Beruf, with value President, must be created. DOM treats the child and its value as separate nodes, so both must be created separately. I find that cumbersome and use another helper. The rest reads and displays the result. One point may puzzle you: we add a child to the root element held in its own variable, root_node, but display variable root, the whole document. How does root know we inserted a child into root_node? Should we update DOM in root somehow? No: the variables simply point to different parts of one DOM tree. Changes through one pointer are immediately visible to all the others, which reference the same tree.
The helpers do the real work. Procedure setXmlHeader() in lines 8–15 is self-explanatory. Function getChildNode() in lines 17–27, returning a child of a given parent, is more substantial. In general, an element can have several children of the same name. Thus function dbms_xmldom.getElementsByTagName() returns a node list, searching by the child name passed to the helper. I then take element n from this list, with its position also passed as a parameter, and return it. Unlike SQL, the list is 0-based, so pass 0 for the first child.
Last comes helper appendChildUnder() in lines 28–47, inserting a child beneath a given parent. This is very cumbersome and really should be hidden in a helper. For reuse, you would probably organize the helpers differently; my aim was easily understood code. First create two nodes: one for the element and one for its value. Text belongs in a separate text node, created independently and later inserted into the element. DOM treats elements and text as specialized nodes, so first convert them to general nodes before inserting them through appendChild(), which expects nodes. First insert the new element beneath the supplied parent, then insert the value as a text child of the new element. The parent now has a child with a value. After all that, we have inserted one child element! Do not blame PL/SQL: W3C defines this DOM programming model, with which PL/SQL aims to remain compatible.
The XSLT processor works similarly, so I will omit an example. First parse both XML and XSLT documents, then instantiate an XSLT processor, configure the transformation details, supply both instances and perform the conversion. Preparation again takes much longer than the transformation itself, which eventually occupies one line—after many preceding lines of code.
dbms_xmlgen, dbms_xmlquery, dbms_xmlstore and dbms_xmlsave
These packages generate, update, store and delete XML data in or from database tables. Since The dbms_xmlgen package and sys_xmlgen already covered generating XML from relational data through PL/SQL, we need not repeat it. This package has functionality comparable to dbms_xmlquery. The sole but important difference is that dbms_xml gen is implemented in C in the database kernel. Thus it is preferable to dbms_xmlquery unless strong reasons suggest otherwise. dbms_xmlquery is part of the XML SQL Utilities (XSU), a collection of XML utilities implemented in Java. I will likewise not discuss packages dbms_xm lsave and dbms_xm lstore separately, since their functionality largely overlaps. Unlike dbms_xmlstore, dbms_xmlsave is also implemented in Java as part of XSU, not the database kernel. Therefore use dbms_xmlgen and dbms_xmlstore whenever possible.
dbms_xmlstore has relatively few, largely self-explanatory methods, such as deletexml(), insertxml() and updatexml(). Its operation is simple: again, a context defines the scope of table settings and parameters. The functions above return the number of processed rows as a number, handling that efficiently too. Only the settings need explanation, as the approach is unusual. Here is an update example. XML matching the result of calling dbms_xmlgen on the target table is used to update it. Recall: converting statement select * from emp through dbms_xmlgen would wrap the instance in element ROWSET and each row in element ROW. Element names would match uppercase column names. Let us assume this standard format.
Identifying the exact row to update requires a where clause. The package fills it from an XML element. We specify that key column and can also specify which columns to update. Otherwise all columns are updated, perhaps to the same value, potentially firing triggers even when watched values did not change. Explicitly naming update columns is therefore best practice, also improving performance by avoiding column analysis. We do so in this example:
select ename, job, sal
fromemp
where empno = 7369;
ENAME JOB SAL
-------- --------- ----------
SMITH CLERK 800
declare
l_ctx dbms_xmlstore.ctxType;
l_rows_processed number;
l_xml_doc clob :=
'<ROWSET>
<ROW>
<EMPNO>7369</EMPNO>
<ENAME>SCHMITZ</ENAME>
<SAL>1200</SAL>
<JOB>ANALYST</JOB>
</ROW>
</ROWSET>';
begin
-- Der Kontext ist die zu aktualisierende Tabelle
l_ctx := dbms_xmlstore.newContext('SCOTT.EMP');
-- Lösche eventuelle Voreinstellungen
dbms_xmlstore.clearKeyColumnList(l_ctx);
dbms_xmlstore.clearUpdateColumnList(l_ctx);
-- Schlüsselspalte ist EMPNO
dbms_xmlstore.setKeyColumn(l_ctx, 'EMPNO');
-- Aktualisiert wird _nicht_ SAL
dbms_xmlstore.setUpdateColumn(l_ctx, 'ENAME');
dbms_xmlstore.setUpdateColumn(l_ctx, 'JOB');
-- Aktualisierung durchführen
l_rows_processed := dbms_xmlstore.updateXML(l_ctx, l_xml_doc);
-- Aufräumen
dbms_xmlstore.closeContext(l_ctx);
end;
/
PL/SQL-Prozedur erfolgreich abgeschlossen.
select ename, job, sal
fromemp
where empno = 7369;
ENAME JOB SAL
-------- --------- ----------
SCHMITZ ANALYST 800Code example: updating XML data with dbms_xmlstore
Setting options and parameters is straightforward. The XML contains all changes, and naming key and update columns provides fine-grained access. This can generically write interface edits back to the database: a procedure accepts data generated by dbms_xmlgen and edited in the interface, then writes them back. It handles one or many rows and controls which columns change, preventing, for example, unintended firing of a trigger on the table’s key column.
Functions insertXML() and deleteXML() work similarly, so no further example is needed. Variable rows_processed then contains the actual number of changed rows.
Other XML packages
Other packages handle specialized XML tasks. I will only summarize their purposes so you can identify those worth investigating for your needs.
dbms_xmlschema
XML instances are often structured files that can validate against XSD. For database validation, register the XSD first. XSD also serves other purposes: deriving schemas from object-relational tables to describe message formats, or handling schema changes when older and newer data must coexist in one table. These and similar tasks are handled bydbms_xmlschema. Schema registration is particularly useful for validating external data inside the database or creating a table that accepts only data conforming to a specific schema.dbms_xmlindex
This package controls XML indexing internals. Any XML instance can be indexed with a specialXMLIndex, updated at each DML operation. XML’s large data volumes can make these updates slow and harm performance.dbms_xmlindexlets you move maintenance ofXMLIndizesasynchronously to quieter periods.dbms_xmltranslations
This package works with XLIFF files (XLIFF = XML Localization Interchange File Format), an OASIS standard for internationalization of applications and messages through XML. XLIFF holds information needed for multilingual applications. The package extracts, adjusts and applies XLIFF files, primarily for multilingual XML documents stored in the database. It is deprecated from 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