Igor Kromin |   Consultant. Coder. Blogger. Tinkerer. Gamer.

I really like the Oracle XMLTABLE feature, which allows you to treat an XML string as if it were a real table. I've been using this feature quite a bit lately and had some difficulties initially around the default namespace so I thought I'd share my findings.

Lets say I had an XML document that looked like this...
 XML
<parent id="123" xmlns="http://igorkromin.net/">
<child id="abc">
<anotherElement>some text</anotherElement>
</child>
</parent>


Now for the purposes of this article I will simply select this from dual like below, however the same approach will work when the data is stored in a real table.
 SQL
select
123 as my_id,
'<ik:parent id="123" xmlns:ik="http://igorkromin.net/">' ||
' <ik:child id="abc">' ||
' <ik:anotherElement>some text</ik:anotherElement>' ||
' </ik:child>' ||
'</ik:parent>' as xml_data
from dual;


The result looks like this...
xmltable1.png




Now lets say I wanted my result to look like this instead...
xmltable2.png


With XMLTABLE you can. The trick is to set the default namespace, otherwise no data will be returned. This only seems to be the case when the XML query string is a non-root node e.g. '/parent' in my case. I found when selecting the root node e.g. '/' the default namespace doesn't matter.

The query below essentially converts values in the XML document to columns that can be used with the rest of the SQL.
 SQL
SELECT
t.my_id,
x.xml_col1,
x.xml_col2,
x.xml_col3
FROM
(
select
123 as my_id,
'<ik:parent id="123" xmlns:ik="http://igorkromin.net/">' ||
' <ik:child id="abc">' ||
' <ik:anotherElement>some text</ik:anotherElement>' ||
' </ik:child>' ||
'</ik:parent>' as xml_data
from dual
) t,
XMLTABLE(
xmlnamespaces(default 'http://igorkromin.net/'),
'/parent'
PASSING XMLType(t.xml_data)
COLUMNS xml_col1 varchar2(100) PATH '@id',
xml_col2 varchar2(100) PATH 'child/@id',
xml_col3 varchar2(100) PATH 'child/anotherElement/text()'
) x
;


Incidentally if the XML was specifying the default xmlns namespace instead of the xmlns:ik namespace, the same XMLTABLE query would work too.

-i

A quick disclaimer...

Although I put in a great effort into researching all the topics I cover, mistakes can happen. Use of any information from my blog posts should be at own risk and I do not hold any liability towards any information misuse or damages caused by following any of my posts.

All content and opinions expressed on this Blog are my own and do not represent the opinions of my employer (Oracle). Use of any information contained in this blog post/article is subject to this disclaimer.
Hi! You can search my blog here ⤵
NOTE: (2022) This Blog is no longer maintained and I will not be answering any emails or comments.

I am now focusing on Atari Gamer.