Generating XML using DBMS_XMLGEN

DBMS_XMLGEN Oracle package is used to convert the result of sql query to a XML format and returns it as a CLOB.

First, Create a sql as below.

stmt_   VARCHAR2(32000) ; 
ctx_    dbms_xmlgen.ctxHandle;
xml_    XmlType;
role_   VARCHAR2(20) := 'ENDUSER';

stmt_ := 'SELECT
               t.role,
               t.description,
               t.created CREATED_DATE,
               CURSOR(SELECT grant_id
                        FROM system_grant_tab
                        WHERE role ='''|| role_||'''
                        ORDER BY nlssort(grant_id, ''nls_sort=binary'')) SYSTEM_GRANTS
    FROM ROLE_TAB t
           WHERE t.role = '''||role_||'''';

Create a new context for sql statement.
ctx_ := Dbms_Xmlgen.newContext(stmt_);

For null handling, three constants are introduced from this package as below.

DROP_NULLS CONSTANT NUMBER := 0 Example: <SYATEM_GRANTS></SYSTEM_GRANTS>

NULL_ATTR CONSTANT NUMBER := 1  Example: xsi:nil="true".

EMPTY_TAG CONSTANT NUMBER := 2; Example: <SYSTEM_GRANTS/>

dbms_xmlgen.setNullHandling(ctx_,2);

Using SetRowStTag Procedure you can set a name for the root element of the document. But you can pass NULL hear also.
dbms_xmlgen.setRowSetTag(ctx_, NULL);

Using SetRowTag Procedure you can set a name for the ROW element. If you donot set this, default value is set as ROW. But, if you pass NULL to hear ROW element will not be presentd.
dbms_xmlgen.setRowTag(ctx_, 'PERMISSION_SET_STRUCTURE');

Then you need to generate xml as a sys.XMLType. There are two overloads for this method. You can pass context or sqlquery.
xml_ := dbms_xmlgen.getXMLType(ctx_);

Then it is required to close context for releasing all the resources associated with it.
Dbms_Xmlgen.Closecontext(ctx_);

Now you can print the result.
Dbms_Output.put_line(xml_.getClobVal)

Then output will be as below

 <PERMISSION_SET_STRUCTURE>
  <ROLE>ENDUSER</ROLE>
  <DESCRIPTION>All required grants for End User</DESCRIPTION>
  <CREATED_DATE>13-SEP-16</CREATED_DATE>
  <SYSTEM_GRANTS>
   <SYSTEM_GRANTS_ROW>
    <GRANT_ID>ADMIN</GRANT_ID>
   </SYSTEM_GRANTS_ROW>
   <SYSTEM_GRANTS_ROW>
    <GRANT_ID>CONNECT</GRANT_ID>
   </SYSTEM_GRANTS_ROW>
   <SYSTEM_GRANTS_ROW>
    <GRANT_ID>DEBUGGER</GRANT_ID>
   </SYSTEM_GRANTS_ROW>
   <SYSTEM_GRANTS_ROW>
    <GRANT_ID>DEFINE SQL</GRANT_ID>
   </SYSTEM_GRANTS_ROW>
   <SYSTEM_GRANTS_ROW>
    <GRANT_ID>DOCUMENT ADMIN</GRANT_ID>
   </SYSTEM_GRANTS_ROW>
   <SYSTEM_GRANTS_ROW>
    <GRANT_ID>SITE ADMIN</GRANT_ID>
   </SYSTEM_GRANTS_ROW>
   <SYSTEM_GRANTS_ROW>
    <GRANT_ID>SHIP ADMIN</GRANT_ID>
   </SYSTEM_GRANTS_ROW>
  </SYSTEM_GRANTS>
 </PERMISSION_SET_STRUCTURE>












Comments

Popular posts from this blog

How to add standard and custom Metadata to PDF using iTextSharp

How to set and get Metadata to image using BitmapMetadata class in C#

How to generate direct line token to start a new conversation between your own client application and bot framework in Java