PL/SQL extract xml nested tags

In PL/SQL, you can extract data from XML documents by using the XMLType data type and various XML functions. When dealing with nested XML tags, it becomes essential to navigate through the hierarchy of tags to extract the desired information. The XMLTable function is particularly useful for this purpose.


Here’s an example of how you can use PL/SQL to extract data from nested XML tags:

  xml_data XMLType;
  -- Sample XML data with nested tags
  xml_data := XMLType('<root>
                          <name>John Doe</name>
                            <city>New York</city>

  -- Extracting data from nested tags using XMLTable
  FOR rec IN (SELECT *
              FROM TABLE(XMLTable('/root/person'
                         PASSING xml_data
                         COLUMNS name VARCHAR2(50) PATH 'name',
                                 city VARCHAR2(50) PATH 'address/city',
                                 state VARCHAR2(2) PATH 'address/state'))) 
    -- Displaying extracted data
    DBMS_OUTPUT.PUT_LINE('Name: ' ||;
    DBMS_OUTPUT.PUT_LINE('City: ' ||;
    DBMS_OUTPUT.PUT_LINE('State: ' || rec.state);

In this example, the XMLTable function is used to break down the XML hierarchy and extract data from nested tags. The ‘/root/person’ parameter in the XMLTable function specifies the XPath expression to navigate to the ‘person’ element within the ‘root’ element. The COLUMNS clause is then used to define the columns to be extracted and their corresponding XPath expressions.

In the loop, each record is processed, and the extracted data is displayed using the DBMS_OUTPUT.PUT_LINE procedure.

This is a simple example, and you may need to adjust the XPath expressions and column definitions based on the structure of your XML data. PL/SQL provides a variety of XML functions, such as EXTRACTVALUE, XMLSequence, and XMLCast, that can be used in combination to handle different XML scenarios.