Thursday, May 10, 2012

XMLElement and namespaces

This post was inspired by the following thread in the OTN forum Formatting data to xml consumes more time. I did some Google searching and did not turn up any decent hits on the topic (or my searching was bad for the day) so I decided to do a quick write up on it.

The first place to start for learning how to generate XML data from an Oracle DB is of course the documentation. This can be found at Generating XML Data from the Database.

If you look through that document, there are not many references to namespaces and namespace prefixes. In fact, only Example 18-6 shows how to add a namespace to a node, but not how to assign a prefix to that node. I created the following example to show how to add a namespace and namespace prefix to nodes in XML.
SELECT XMLElement("t:global-instance",
                  XMLAttributes('' AS
                  XMLForest('c2' AS "t:child2",
                            'c3' AS "t:child3"),
                  XMLElement(evalname('t1:' || dummy), 'c4')).getClobVal() rslt 
  FROM dual;
which generates
<t:global-instance xmlns:t="">

That shows the basics for adding a prefix when using XMLElement and XMLForest. If you are using or later, you can also use EvalName to generate the node name instead of hard-coding it as earlier versions required. In that case, I showed how to include the namespace prefix for EvalName as well. Yes it really is that simple. You just type in the prefix you want to use.

No comments:

Post a Comment