XML DOM. Get element by name on first child level

Andrey Khataev picture Andrey Khataev · Feb 3, 2012 · Viewed 11.3k times · Source

I have such xml:

<root>
  <element1>
     <doc>2</doc>
  </element1>
  <doc>1</doc>
</root>

I want to get element on first child level after root element (value = 1). If I do it through nodelist (pl/sql version of xmldom api):

nl := getElementsByTagName(rootnode,'doc');
len := xmldom.getLength(nl);
IF LEN>0 THEN
    N:=xmldom.item(nl, 0);
END IF;
RETURN N;

first element in list would be element with value = 2. How could I process only through child nodes of first child level without looping through elements?

Answer

user272735 picture user272735 · Feb 3, 2012

With DBMS_XMLDOM use GETCHILDRENBYTAGNAME:

declare
  xml constant xmltype := xmltype(
'<root>
  <element1>
     <doc>2 - two</doc>
  </element1>
  <doc>1 - one</doc>
</root>'
);
  doc constant dbms_xmldom.domdocument := dbms_xmldom.newdomdocument(xml);

  root_elem constant dbms_xmldom.domelement :=
    dbms_xmldom.getdocumentelement(doc);

  doc_nodes constant dbms_xmldom.domnodelist :=
    dbms_xmldom.getchildrenbytagname(root_elem, 'doc');
begin
  declare
    last_index constant pls_integer := dbms_xmldom.getlength(doc_nodes) - 1;
    node dbms_xmldom.domnode;
    text_node dbms_xmldom.domnode;
  begin
    for i in 0 .. last_index loop
      node := dbms_xmldom.item(doc_nodes, i);
      text_node := dbms_xmldom.getfirstchild(node);
      dbms_output.put_line('i = ' || i ||
                           ' name = ' || dbms_xmldom.getnodename(node) ||
                           ' type = ' || dbms_xmldom.getnodetype(node) ||
                           ' text = ' || dbms_xmldom.getnodevalue(text_node));
    end loop;
  end;
end;
/

Output:

SQL> @so24
i = 0 name = doc type = 1 text = 1 - one

PL/SQL procedure successfully completed.

SQL>