views:

1247

answers:

2

In Oracle, you can use the XMLElement() function to create an element, as in:

XMLElement('name', 'John')

But how to create an element in a specific namespace? For instance, how to create the following element:

<my:name xmlns:my="http://www.example.com/my"&gt;John&lt;/my:name&gt;
+1  A: 

Instead of XMLElement() use:

XMLType('<my:name xmlns:my="http://www.example.com/my"&gt;John&lt;/my:name&gt;')

Yes, it is that simple.

Alessandro Vernet
+1  A: 

You can also use XMLAttribute:

select xmlelement("my:name",
     xmlattributes('http://www.example.com/my' as "xmlns:my"),
     'John'
       )
from dual

Will return:

<my:name xmlns:my="http://www.example.com/my"&gt;John&lt;/my:name&gt;

You can also check that Oracle recognizes this as a namespace (other than you are not getting a namespace prefix "my" is not declared error):

select xmlelement("my:name",
        xmlattributes('http://www.example.com/my' as "xmlns:my"),
        'John'
       ).getnamespace()
from dual

Will return:

http://www.example.com/my
Craig
Ah, interesting. You can really use an xmlattributes() to define a namespace? Feels like a stretch to me, but if this works, this is a good one!
Alessandro Vernet