Extract  Node name and values from an  XML Document   June  3, 2012

In this example we will show how to extract node names (Tags) given an XML document.

We will write to program units for this purpose

The first one will take XML content as an input and will return a variable of type DBMS_XMLDOM.DOMDocument;

the second will take the DOMDocument and display the name of the tags

FIRST Program UNIT

Input:  XML  string

Output: DOMDocument

CREATE OR REPLACE FUNCTION makexmlDOMDoc (xml_content clob) return DBMS_XMLDOM.DOMDocument as

    l_parser dbms_xmlparser.Parser;

    my_doc DBMS_XMLDOM.DOMDocument;

begin

    l_parser := dbms_xmlparser.newParser;

-- Parse the document and create a new DOM document.

    dbms_xmlparser.parseClob(l_parser, xml_content);

-- The xml parsed CLOB is not transfered to a variable called my_doc

    my_doc := dbms_xmlparser.getDocument(l_parser);

-- Free resources associated with the CLOB and Parser now they are no longer needed.

    dbms_xmlparser.freeParser(l_parser);

return my_doc;

end;

Second Program Unit

Input:  DocDocument

output: List of varchars indication the tags in the document

CREATE OR REPLACE  PROCEDURE getElements(xmldoc DBMS_XMLDOM.DOMDocument) IS
    node_list DBMS_XMLDOM.DOMNodeList;
    node DBMS_XMLDOM.DOMNode;
    node_name varchar(4000);
    len number;

BEGIN
-- get all elements
    node_list := DBMS_XMLDOM.getElementsByTagName(xmldoc, '*');
    len := DBMS_XMLDOM.getLength(node_list);


FOR i IN 0 .. len - 1 LOOP
    node := DBMS_XMLDOM.item(node_list, i);
    node_name := DBMS_XMLDOM.getNodeName(node) || ' ' || DBMS_XMLDOM.getNodeValue(DBMS_XMLDOM.getFirstChild(node));

    DBMS_OUTPUT.PUT_LINE (node_name);   
END LOOP;
    DBMS_OUTPUT.PUT_LINE ('');
END getElements;
 

Example to verify

begin

        getElements(makexmlDOMDoc('<college>

                                                                <master>

<id>10</id>

<name>REALSOFT</name>

<row>

<student_id>1</student_id>

<student_name>Ahmad</student_name>

</row>

<row>

<student_id>2</student_id>

<student_name>Samia</student_name>

</row>

<row>

<student_id>3</student_id>

<student_name>Tareq</student_name>

</row>

    </master>

</college>'));

end;

 

result is

 

college

master

id 10

name REALSOFT

row

student_id 1

student_name Ahmad

row

student_id 2

student_name Samia

row

student_id 3

student_name Tareq