Tuesday, 28 April 2009

Navigating XML in Oracle

A few code snippets for navigating and extracting dynamically from XML in PL/SQL.

--The executable section of the traverse_and_display procedure. 
BEGIN
-- get all elements
nodes := xmldom.getElementsByTagName (doc, '*');

-- loop through elements
FOR node_index IN 0 .. xmldom.getLength (nodes) - 1
LOOP
one_node := xmldom.item (nodes, node_index);

display_element (one_node);

node_map := xmldom.getAttributes (one_node);

FOR attr_index IN
0 .. xmldom.getLength (node_map) - 1
LOOP
display_attribute (node_map, attr_index);
END LOOP;
END LOOP;
END traverse_and_display;



-- The code required for displaying the name and value of an element.
PROCEDURE display_element (node IN xmldom.DOMNode)
IS
one_element xmldom.DOMElement;
value_node xmldom.DOMNode;
BEGIN
one_element := xmldom.makeElement (node);
DBMS_OUTPUT.put_line ('Element: ' ||
xmldom.getTagName (one_element
)
);
value_node := xmldom.getFirstChild (node);
DBMS_OUTPUT.put_line ('Value: ' ||
xmldom.getNodeValue (value_node
)
);
END;



--Displaying the value of an attribute.
PROCEDURE display_attribute (
node_map IN xmldom.DOMNamedNodeMap,
attr_index IN PLS_INTEGER
)
IS
one_node xmldom.DOMNode;
attrname VARCHAR2 (100);
attrval VARCHAR2 (100);
BEGIN
one_node := xmldom.item (node_map, attr_index);
attrname := xmldom.getNodeName (one_node);
attrval := xmldom.getNodeValue (one_node);
DBMS_OUTPUT.put_line (' ' ||
attrname || ' = ' || attrval
);
END;

No comments: