Alessandro Lacava

on Designing and Developing Software. In love with Functional Programming.

How to Store and Extract XML Data In and From an Oracle DataBase (DB)

Here are some snippets of code showing how to accomplish this:

1
CREATE TABLE SampleTable (id number primary key, person XMLType)

This first example creates a table with only two columns: id and person. The first is the PK of the table and the second is of XMLType type. The latter is going to contain our XML data.

Now let’s insert one row in the table.

1
INSERT INTO SampleTable VALUES (1, XMLType('XMLString'))

Where you must replace XMLString with any string representing XML. For example, you can replace it with:

1
2
3
4
5
6
7
<persons>
  <person>
    <surname>Lacava</surname>
    <name>Alessandro</name>
    <date_OF_BIRTH DAY="31" MONTH="01" YEAR="1976" />
  </person>
</persons>

I decided to decode the date of birth that way in order to show you (in the next example) how to retrieve, apart from a common XML node, an attribute as well.

1
2
3
SELECT extractValue(person, '/PERSONS/PERSON/SURNAME') AS surname,
  extractValue(person, '/PERSONS/PERSON/DATE_OF_BIRTH/@YEAR') AS year_of_birth
FROM SampleTable

This last example extracts the surname and the year of birth from the XML data represented by the person column that is of XMLType type. As you can see to extract the XML data you use regular XPath expressions.

Note: If your XML is using a namespace you will have to indicate it using the following syntax:

1
extractValue(column_name, XPath_Expression, 'xmlns="namespace_URI"')

where XPath_Expression is the XPath expression used to extract the value you’re interested in and namespace_URI is the URI indicating your namespace.

One last note: You can use XML Data inside an Oracle DB from version 9.0.2 on.

Comments