XML technologies / Oracle & XML / Working with XML / The data type “XMLType”

(Excerpt from "Oracle PL/SQL: Das umfassende Handbuch", chapter 16 "Arbeiten mit XML", by Jürgen Sieben)

We begin our tour of Oracle’s XML support with the data type XMLType. This is an object-oriented data type implemented in C. As an object-oriented type, XMLType can define table columns. Tables can also be derived directly from this type.

Using XMLType as a table or column type

Let us look at an example of each use:

create table xml_test_1(id number, xml_content XMLType);


Tabelle wurde erstellt.

In this example, table column xml_content has type XMLType. Initially this type implies no special storage: technically, the data is stored in a CLOB column. Oracle nevertheless “knows” more about these data, because methods defined in the type provide access to the XML structures. Since this is XML, Oracle can use XML processing to search, filter parts or transform entire XMLType instances using XSLT. The next example creates an object-oriented table of type XMLType:

create table xml_test_2 of xmltype;


Tabelle wurde erstellt.

This statement may look obscure if you have not worked with object-oriented types. Let us describe the table to see how it appears in the Data Dictionary:

desc xml_test_2;


Name                       Null?    Typ
-------------------------- -------- -----------------------
                                    TABLE of PUBLIC.XMLTYPE

This is not particularly illuminating yet. To learn more about this table type, we insert an XML instance. Because the type is object-oriented, we must first create an instance using its constructor function, which has the same name as the type, and pass it a string formatted as XML:

insert into xml_test_2
  values (XMLType('<Foo/>'));


1 Zeile wurde erstellt.

This very short, simple XML instance has evidently been inserted. What do we see when we read the row back from the database?

select *
  from xml_test_2;


SYS_NC_ROWINFO$
-----------------------
<Foo/>

Code example: variants for creating XMLType tables and columns

The system has evidently generated the column name SY_NC_ROWINFO$ for this table—how pretty, and so memorable! We have seen similar behavior with table(), which converts the result of a table function or cursor into a regular table accessible through SQL. In that case Oracle generated the column name COLUMN_VALUE. Oracle has likewise defined the alias OBJECT_VALUE for the column above, which can be used interchangeably with SYS_NC_ROWNIFO$. The XML instance we inserted has also been returned. Our first XML table, with XMLType as its column type, would behave similarly. Such an XMLType column is therefore used just like scalar data types:

insert into xml_test_1
  values (1, XMLType('<Foo/>'));


1 Zeile wurde erstellt.

select *
  from xml_test_1;


        ID XML_CONTENT
---------- ------------
        1 <Foo/>

Code example: inserting an XML instance into a table

In this variant, the type works like any other data type, except that, as with all object-oriented types, we need a constructor. So what makes it powerful? So far, it seems no different from a string; the reasons for choosing XMLType as a data type are not yet clear. Let us store a larger XML instance and examine the possibilities it offers:

insert into xml_test_1
values (1, XMLType('<Mitarbeiter id="12345"><Name>Müller</Name></Mitarbeiter>'));


1 Zeile wurde erstellt.

This statement inserts an XML instance containing a Mitarbeiter element with an attribute id and a child element Name. This slightly more complex instance lets us demonstrate the format’s strength. Suppose we need the value of attribute id. In this simple example, extracting it with conventional text tools, perhaps a regular expression, seems easy. With larger files, however, this could cause serious problems. Instead, we use a rather strange-looking syntax:

select x.xml_content.extract('/Mitarbeiter/@id').getnumberval() id
from xml_test_1 x


        ID
----------
     12345

Code example: Oracle understands XML structure.

The example accesses column xml_content through the table alias x. Such an alias is required for accessing database objects. This “pointer” lets us access the object-oriented type and call one of its methods: extract. We pass this function an expression in XPath to navigate within an XML instance. This uses an official XML standard rather than Oracle technology. The notation @id moves from the element hierarchy to attribute id, which contains the required information. The function returns a string containing the value of attribute id and passes it to method getNumberVal(). This converts the string into a number and returns it.

New features in version 12c
Before you become too accustomed to this approach, note that the XMLType functions are deprecated in database version 12c in favor of the XQuery functions XMLExtract and XMLTable, discussed under Extracting relational data from XML.

XMLType member functions

As we have seen, data type XMLType provides a number of methods, known as member functions. To see the available methods, use

desc XMLType

. Let us organize the list of functions a little.

Constructors and XML creation functions

First come the constructors and XML creation functions. These include all overloads with the same name as the data type. Overloads exist for varchar2, CLOB, BLOB, bfile, cursor variables and the data type anydata, and even for undefined, used to convert an object into XML. Thus, the constructor XMLType() can turn almost anything into XML, provided its contents can somehow pass as XML. Examining these constructors’ declarations shows that they all return themselves (self). This is the pointer to the object instance discussed earlier, which controls access to instances of this type.

There are also the functions createXml with their overloads. These largely duplicate the constructor methods. Notice that they are declared static, meaning they can be used without first creating an instance. That is appropriate, since creating an instance is their purpose. They are less common in practice; constructors are normally used instead. I occasionally see this approach when converting object types to XML.

Methods for analyzing XML instances

This group provides information about the state of the stored XML instance. It includes functions such as isSchemaValidated() or isFragment() or isSchemaValid(), as well as functions returning the root element or the name of the validating schema. They are important for maintenance and sometimes for trigger programming. Another key function is existsNode(), which checks whether the instance contains a specified element.

Methods for editing XML instances

Here we find methods such as appendChildXML(), insertXmlBefore() and deleteXml(). Also important in this group are extract() and extractValue(), used to extract data and convert XML instances into relational structures. Another important function is transform(), which converts an XML instance into another form using a supplied XSLT. For example, a stylesheet could convert XML information into HTML, which could then be written directly to an HTTP stream and displayed in a browser. Further examples of these methods follow later.

Transforming XML with XSLT

A particularly useful feature of XMLType is its ability to be transformed directly with XSLT. This technology uses XML mechanisms to convert XML instances into other output formats. Almost any output format is possible, though HTML and differently structured XML are common. Consider a simple scenario: an XML message must have a different structure for each recipient while remaining XML. Several recipient-specific XSLT instances could be stored in a table. To transform an XML instance for a recipient, reference the table, select the appropriate XSLT and perform the transformation in one step.

Central to this capability is member function transform of XMLType. It expects an XSLT instance and transforms the XMLType instance, returning the transformed XMLType instance. Let us look at an example.

Our input XML comes from a view returning the employees as an XMLType instance:

create or replace view emp_xml_vw as
select xmlelement("Mitarbeiterliste",
              xmlagg(
               xmlelement("Mitarbeiter",
                xmlattributes(
                    empno "id",
                    hiredate "einstellDatum",
                   deptno "abteilungId"
                 ),
                xmlforest(
                initcap(ename) "Name",
                initcap(job) "Beruf",
                sal "Gehalt"
             )
           )
        order by ename
      )
    ) resultat
  from emp;


View created.

Code example: creating XMLType instances

We also need a small table to hold the XSLT instances:

create table emp_xslt(
       id number,
       xslt xmltype,
       constraint pk_emp_xslt primary key(id)
 );


Table created.

Code example: creating a table for XSLT instances

Rather than dazzle you with my boundless XSLT expertise (though of course I could ;-), I will keep the task simple: a recipient needs an XML list of our company’s managers, generated from the employee list. At the same time, element Mitarbeiterliste should be renamed ManagerListe.

Here is the XSLT for this task:

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>
    <xsl:template match="/">
        <xsl:apply-templates/>
    </xsl:template>
    <xsl:template match="Mitarbeiterliste">
        <ManagerListe>
            <xsl:apply-templates select="Mitarbeiter[Beruf = 'Manager']"/>
        </ManagerListe>
    </xsl:template>
    <xsl:template match="Mitarbeiter">
        <xsl:copy-of select="."/>
    </xsl:template>
</xsl:stylesheet>

Code example: a simple stylesheet for transforming the XML instance

XSLT instances define a namespace xsl grouping the transformation instructions. All XML elements referencing this namespace are transformation instructions. Elements not referencing it are copied unchanged into the output tree.

Let us examine some parts. First, the stylesheet contains three templates. A template is a processing rule for an XML element. Attribute match determines which element it applies to. Element specifications are XPath expressions that navigate within an XML document much like a folder hierarchy. Knowing the current position in the XML tree is essential: XPath paths are usually relative to it. In the first template we are at the instance root, above the root element, hence the XPath expression / in attribute match. This template merely moves the current position to root element Mitarbeiterliste and calls the templates defined for it.

The template for Mitarbeiterliste creates a new XML element Managerliste and moves the current tree position successively to all child elements Mitarbeiter whose child element Beruf has value Manager. The node test in the select attribute of instruction xsl:apply-templates controls this.

The template for Mitarbeiter is then called three times, since the XML instance contains three managers. It simply copies element Mitarbeiter with all attributes and children into the output tree. We then return to the template for Mitarbeiterliste, append the end tag of element ManagerListe and finish the transformation. The resulting XML instance is:

<?xml version="1.0" encoding="UTF-8"?>
<ManagerListe>
    <Mitarbeiter id="7698" einstellDatum="1981-05-01" abteilungId="30">
        <Name>Blake</Name>
        <Beruf>Manager</Beruf>
        <Gehalt>2850</Gehalt>
    </Mitarbeiter>
    <Mitarbeiter id="7782" einstellDatum="1981-06-09" abteilungId="10">
        <Name>Clark</Name>
        <Beruf>Manager</Beruf>
        <Gehalt>2450</Gehalt>
    </Mitarbeiter>
    <Mitarbeiter id="7566" einstellDatum="1981-04-02" abteilungId="20">
        <Name>Jones</Name>
        <Beruf>Manager</Beruf>
        <Gehalt>2975</Gehalt>
    </Mitarbeiter>
</ManagerListe>

Code example: transformation result

That should illustrate the principle. Now we copy the stylesheet into table emp_xslt and transform the query result into the new format directly in SQL:

insert into emp_xslt
  values (10, xmltype(q'{
  <?xml version="1.0" encoding="UTF-8"?>
  <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
     <xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>
     <xsl:template match="/">
           <xsl:apply-templates/>   
     </xsl:template>
     <xsl:template match="Mitarbeiterliste">
        <ManagerListe>
            <xsl:apply-templates select="Mitarbeiter[Beruf = 'Manager']"/>
        </ManagerListe>
     </xsl:template>
     <xsl:template match="Mitarbeiter">
            <xsl:copy-of select="."/>
     </xsl:template>
  </xsl:stylesheet>
    }'));


1 row created.


commit;


Commit complete.

Code example: storing the XSLT instance in the database

The rest is surprisingly easy:

select e.resultat.transform(x.xslt) umwandlung
     from emp_xml_vw e
   cross join emp_xslt x
   where x.id = 1;


UMWANDLUNG
--------------------------------------------------------
<?xml version="1.0" encoding="UTF-8"?>
<ManagerListe>
    <Mitarbeiter id="7698" einstellDatum="1981-05-01" abteilungId="30">
        <Name>Blake</Name>
        <Beruf>Manager</Beruf>
        <Gehalt>2850</Gehalt>
    </Mitarbeiter>
    <Mitarbeiter id="7782" einstellDatum="1981-06-09" abteilungId="10">
        <Name>Clark</Name>
        <Beruf>Manager</Beruf>
        <Gehalt>2450</Gehalt>
    </Mitarbeiter>
    <Mitarbeiter id="7566" einstellDatum="1981-04-02" abteilungId="20">
        <Name>Jones</Name>
        <Beruf>Manager</Beruf>
        <Gehalt>2975</Gehalt>
    </Mitarbeiter>
</ManagerListe>

Code example: transforming XML in SQL

Of course, SQL/XML could perform such a transformation too. This approach is elegant because a generic XML format can produce arbitrary output formats, including CSV, using simple recipient-specific XSLT instances stored in a table. It only requires storing several XSLT instances under appropriate IDs in table emp_xslt. Stylesheet creation can also be delegated to other developers, who need not know SQL/XML; database developers likewise need not necessarily learn XSLT.

  

 

 

 

back to top