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...
Now lets say I wanted my result to look like this instead...
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