Monday, 23 April 2018

PL/SQL: Sample code to insert/import an xml object into an xml structure using dbms_xmldom

In one of my project, I had to modify and existing code which uses dbms_xmldom to create an xml structure.
The requirement is to instert an xml struture as a node in the main xml. The below given is a sample which shows how to insert an xml into another xml when working with dbms_xmldom.
 DECLARE  
  v_doc               dbms_xmldom.domdocument;  
  v_root_node         dbms_xmldom.domnode;  
  v_grant_parent_node dbms_xmldom.domnode;  
  v_parent_node       dbms_xmldom.domnode;  
  v_child_xml         xmltype := xmltype('<children>  
                                            <child>ABC</child>  
                                            <child>XYZ</child>  
                                          </children>');  
  v_childdoc         dbms_xmldom.domdocument;  
  v_childdocelement  dbms_xmldom.domelement;  
  v_childnode        dbms_xmldom.domnode;  
 BEGIN  
  v_doc := dbms_xmldom.newdomdocument;  
  dbms_xmldom.setversion(v_doc,'1.0');  
  v_root_node         := dbms_xmldom.makenode(v_doc);  
  v_grant_parent_node := dbms_xmldom.appendchild(v_root_node  
                                     ,dbms_xmldom.makenode(dbms_xmldom.createelement(v_doc  
                                     ,'grantparent')));  
  v_parent_node       := dbms_xmldom.makenode(dbms_xmldom.createelement(v_doc  
                                     ,'parent'));  
  v_root_node         := dbms_xmldom.appendchild(v_grant_parent_node,v_parent_node);
  
  dbms_output.put_line('Before Adding Children:');  
  dbms_output.put_line(dbms_xmldom.getxmltype(v_doc).getclobval());  
  
  --Create the document using the child xml  
  v_childdoc := dbms_xmldom.newdomdocument(v_child_xml);  
  
  --Get the root element from the child document created above  
  v_childdocelement := dbms_xmldom.getdocumentelement(v_childdoc);  
  
  --Get the DomNode from the child document  
  v_childnode := dbms_xmldom.importnode(v_doc ,dbms_xmldom.makenode(v_childdocelement),TRUE);  
  
  --Converts the DomNode to a DomElement  
  v_childdocelement := dbms_xmldom.makeelement(v_childnode);  
  
  --Add the child element to the Parent Node.  
  v_root_node := dbms_xmldom.appendchild(v_parent_node,dbms_xmldom.makenode(v_childdocelement));  
  
  dbms_output.put_line('After Adding Children:');  
  dbms_output.put_line(dbms_xmldom.getxmltype(v_doc).getclobval());  
 END;  

Output:

 Before Adding Children:  
 <?xml version="1.0"?>  
 <grantparent>  
  <parent/>  
 </grantparent>  
 After Adding Children:  
 <?xml version="1.0"?>  
 <grantparent>  
  <parent>  
   <children>  
    <child>ABC</child>  
    <child>XYZ</child>  
   </children>  
  </parent>  
 </grantparent>  


Feel free to point out if anything is missing/wrong in this blog.

1 comment: