Tuesday, October 07, 2008

Insert, Append, or Update an XML element to an XML document using Oracle PL/SQL

Oracle allows you to quickly insert or append an XML element to a path inside an XML document using insertchildxml.

select
insertchildxml(v_xmltype,
'/my/xpath',
lower('elementname'),
XMLType('stuff'))
from dual;


Gotchas: You must use a select statement. Argument 3 must match the element inside argument 4.

If you are modifying attributes, you can use updatexml-- but it is obnoxious because if the attribute doesn't exist, updatexml fails silently. So, if unsure, you need to user insertxml to add the attribute and if it throws an exception, then attempt an update. Like so:

   BEGIN
select insertchildxml(v_xml, '//myxpath', '@myattribute',
v_newvalue) into v_xml from dual;
EXCEPTION -- if @myattribute attribute exists, insert will fail, so update instead
WHEN OTHERS THEN
select updatexml(v_xml, '//myxpath/@myattribute', v_newvalue)
into v_xml from dual;
END;

No comments:

Labels

Blog Archive

Contributors