XML technologies / Oracle & XML / XML queries / Editing XML instances in SQL

(Excerpt from "Oracle SQL: Das umfassende Handbuch", chapter 17 "XML-Abfragen", by Jürgen Sieben)

Existing XML instances can also be updated. This does not mean replacing the entire XML instance in a table cell with a new version, but making fine-grained changes to attribute or element values, appending child elements or deleting subtrees of the XML document. A set of scalar functions makes this possible; they can be used in ordinary update statements and navigate the XML instance using XPath.

To demonstrate these functions, I will store the employee lists created under A simple example in a table named dept_emp_xml. You now know enough SQL for me to omit the necessary ctas statement here. It is included in the book’s script. The table now contains three rows with the corresponding XML instances. Here is an excerpt from its first row:

select *
 from dept_emp_xml
 where deptno = 10;


   DEPTNO       LISTE
---------- -----------------------------------------------------
            
      10        <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>Miller</Name>
                        <Beruf>Clerk</Beruf>
                        <Gehalt>1.300,00€</Gehalt>
                    </Mitarbeiter>
                    <Mitarbeiter einstellDatum="1981-11-17" id="7839">
                        <Name>King</Name>
                        <Beruf>President</Beruf>
                        <Gehalt>5.000,00€</Gehalt>
                    </Mitarbeiter>
                </Mitarbeiterliste>

Code example: an employee list in the dept_emp_xml table

As you can see, instead of RESULTAT I chose the more suitable LISTE as the column name, since it fits somewhat better.

Basics of scalar functions for editing XML

The scalar functions I will introduce share certain features that we should discuss first. They operate on a copy of the actual XML instance. All scalar functions do this (including, for example, upper): they calculate the result and replace the original value if no error occurs. This is normally unproblematic, but an XML instance can be larger, perhaps even much larger, than a simple number. That makes this behavior significant. Whether the resulting XML instance then overwrites the entire instance in the database depends partly on how the database is administered.

Brief digression: XML storage formats in the database
XML instances need not be stored only as clob in the database (they remain XML, but the simplest storage mechanism is a clob). An XML table can also be based on an XML Schema definition (XSD) file. These files describe the structure
of an XML instance and can be extended with annotations (attributes from the namespace Oracle XML DB) to tell the database how to store the instance in a network of object-relational tables. Broadly speaking, the XML instance is shredded into its components and stored across tables created by Oracle. 
If an XML instance is stored this way, the update statement really updates only the affected tables. However, the XMLBinary storage format introduced in database version 11.2 makes object-relational XML storage less likely. It stores an optimized, parsed binary representation of the XML file, already validated if a schema is referenced. Combined with the XMLIndex index type, this is extremely fast and usually makes object-relational storage unnecessary.

But let us stay with the usual case: technically, an XML instance is an intelligent clob, modified at a fine-grained level by the following functions. This modification is performed on a copy of the instance, and the update statement replaces the existing instance completely.

All XML functions in this group accept an optional parameter specifying the element’s namespace. Remember: 90% of XML errors stem from two sources—XPath expressions and namespace problems. Keep this option in mind to avoid hours of debugging. If an element is in a namespace other than the null namespace (in other words, if any namespace is specified, whether as a default namespace or with a namespace prefix), you must also supply it; otherwise nothing is found. The namespace parameter is passed last to the functions.

The following table provides an overview of the functions available for each task.

Task

Function

Modify existing XML nodes

updatexml

Delete existing XML nodes

deletexml

Insert new XML nodes

appendchildxml insertchildxml insertchildxmlbefore insertchildxmlafter insertxmlbefore insertxmlafter

Table: available functions for editing XML

As a rule, use these functions for their designated tasks even when another approach is possible. For example, updatexml can insert new nodes into a tree, but less efficiently than the specialized functions, which also give you more control over the process.

Another common feature: these functions support XPath 1.0 expressions (as of Oracle 11.2), and even that incompletely. You must test which features Oracle accepts and which do not work.

Modifying existing XML instances

Let us begin by updating an employee’s job. Mr King should now be PRÄSIDENT. We use the function updatexml:

update dept_emp_xml
          set liste = updatexml(liste,
             '/Mitarbeiterliste/Mitarbeiter[3]/Beruf/text()',
             'PRÄSIDENT')
      where deptno = 10;


1 Zeile wurde aktualisiert.

Code example: updating an XML node

Unfortunately, the long XPath expression makes the formatting rather awkward. What did I do? First, I requested an updated version of our XML instance using updatexml. The current XML instance is passed to the function as a column. The second parameter is an XPath expression identifying the node to change within the XML instance. Notice that this expression contains the XPath function text(), so it returns only the element’s text node. Otherwise, it would return the complete Beruf element with its contents. The third parameter therefore expects text, not an XML element. Conversely, if the XPath expression identified a node, an XMLType instance would be required to replace the existing node. This function is something of a Swiss Army knife within this group: it also accepts multiple XPath/value pairs to update several nodes in one operation. Here is an example, this time updating with XMLType:

update dept_emp_xml
       set liste =
          updatexml(
             liste,
             '//Mitarbeiter[3]/Beruf',
             XMLType('<Beruf>PRÄSIDENT</Beruf>'),
             '//Mitarbeiter[2]/Name',
             XMLType('<Name>Müller</Name>'))
      where deptno = 10;


1 Zeile wurde aktualisiert.

Code example: updating two nodes in one statement

Here I chose the abbreviated XPath expression // to find any child element named Mitarbeiter in the XML instance. This is purely for presentation, to shorten the long XPath expressions. With more space to write the function, it becomes clearer, much as a decode function can be clear. The advantage is that we no longer have to read, parse and update the entire XML instance ourselves. The disadvantage is that the database must now do exactly that: in use, XMLType is equivalent to a DOM tree. Thus, larger XML instances cost more to process. But XMLType is no replacement for a relational data model. Storing information as XMLType in the database can be very useful, for example for narrative texts that are difficult to store otherwise yet must remain indexable and searchable. When structured information arrives in XML, however, relational tables will probably be preferable because they are faster and use less storage. For all its advantages, XML is extremely verbose. Updating XML instances with these functions should therefore not be needed as often as updating structured information in a table.

One more point: in theory, this updatexml function can also change an XML instance’s structure, moving subtrees or changing element names. Usually, however, XSLT is preferable for such transformations. The functions discussed here mainly serve to change specific XML element values. Consider this scenario: in a message-based application, I once generated the messages themselves through a SQL query. For various reasons, some element values could only be set later. A simple XML statement using updatexml handles this very well.

Deleting existing elements

The function for deleting elements is straightforward: pass deletexml the XML instance, an XPath expression and, if needed, a namespace. The node is then gone. Here is a brief example: the president should be removed from the XML for department 10.

update dept_emp_xml
          set liste = deletexml(liste,
               '//Mitarbeiter[Name="King"]')
     where deptno = 10;


   1 Zeile wurde aktualisiert.


select liste
        from dept_emp_xml
    where deptno = 10;


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>Miller</Name>
        <Beruf>Clerk</Beruf>
        <Gehalt>1.300,00€</Gehalt>
    </Mitarbeiter>
</Mitarbeiterliste>

Code example: deleting an element from an XML instance

Inserting new elements

Most functions insert new elements. Many are very similar, so identifying their structure makes them easy to survey.

First distinguish between inserting a child element and a sibling element. To insert a sibling before or after the target selected by XPath, use insertxml (before or after). To create a child beneath the target element, use the function whose name contains child. appendchildxml places the child last within the target element; insertchildxml without a position places it somewhere within the element. With schema-based XML, the schema may determine the position; otherwise it is arbitrary. insertchildxmlbefore or -after places the child at a position in an element list that must be passed to the function. This may sound complex, but it means the following: if an XML element Mitarbeiter occurs repeatedly in Mitarbeiterliste, you can insert the new element before or after, for example, the third employee in the existing list. Supply an XPath expression (here: Mitarbeiter[3]) identifying the list element before or after which the new element belongs.

To summarize, this group inserts new elements into an existing XML instance. We distinguish between inserting a sibling before or after an existing element (insertxml) and inserting a child of an existing element (insertchildxml). The element’s position is generally controlled by before and after; in lists of child elements, we can also insert a child last (appendchildxml) or somewhere within the list (insertchildxml).

With that introduction, the functions are no longer difficult to understand. Here is an example using insertxmlbefore, appendchildxml and insertchildxmlbefore:

-- Ein Geschwisterelement vor dem zweiten Mitarbeiter einfügen
update dept_emp_xml
       set liste =
         insertxmlbefore(liste,
              '//Mitarbeiter[2]',             
         xmltype(
              '<Mitarbeiter einstellDatum="2001-03-12">' ||
              ' <Name>Meier</Name>' ||
              ' <Beruf>Halbkreisingenieur</Beruf>' ||
              ' <Gehalt>3.500,00€</Gehalt>' ||
              '</Mitarbeiter>'))
     where deptno = 10;


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="2001-03-12">
        <Name>Meier</Name>
        <Beruf>Halbkreisingenieur</Beruf>
        <Gehalt>3.500,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>


-- Ein Kindelement als letzes anfügen
update dept_emp_xml
       set liste =
         appendChildXML(liste,
              '/Mitarbeiterliste',
           xmltype(
              '<Mitarbeiter einstellDatum="2001-03-12">' ||
              ' <Name>Meier</Name>' ||
              ' <Beruf>Halbkreisingenieur</Beruf>' ||
              ' <Gehalt>3.500,00€</Gehalt>' ||
              '</Mitarbeiter>'))
where deptno = 10;


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>
    <Mitarbeiter einstellDatum="2001-03-12">
        <Name>Meier</Name>
        <Beruf>Halbkreisingenieur</Beruf>
        <Gehalt>3.500,00€</Gehalt>
    </Mitarbeiter>
</Mitarbeiterliste>


-- Ein Kindelement vor dem ersten Mitarbeiter einfügen
update dept_emp_xml
      set liste =
          insertChildXMLbefore(liste,
              '/Mitarbeiterliste',
              'Mitarbeiter[1]',
              xmltype(
              '<Mitarbeiter einstellDatum="2001-03-12">' ||
              ' <Name>Meier</Name>' ||
              ' <Beruf>Halbkreisingenieur</Beruf>' ||  
              ' <Gehalt>3.500,00€</Gehalt>' ||
              '</Mitarbeiter>'))
    where deptno = 10;


LISTE
----------------------------------------------------------------
<Mitarbeiterliste abteilung="10">
    <Mitarbeiter einstellDatum="2001-03-12">
        <Name>Meier</Name>
        <Beruf>Halbkreisingenieur</Beruf>
        <Gehalt>3.500,00€</Gehalt>
    </Mitarbeiter>
    <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: some XML element insertion operations

Note the following: in the first update statement, XPath identifies the sibling element ( Mitarbeiter), whereas functions inserting children naturally require the parent element, Mitarbeiterliste. If you also specify Mitarbeiter here, the new Mitarbeiter element is nested inside the specified Mitarbeiter element. The final update statement also receives, besides XPath for the parent, an XPath expression for the list element before or after which the new element should be inserted.

All update statements were undone with rollback before the next update statement was executed, so you need not wonder where all the Meiers went. One semicircle engineer is surely enough for a department …

  

 

 

 

back to top