Traverse all the nodes of an XML document?

Alex picture Alex · Oct 4, 2011 · Viewed 8k times · Source

I want to traverse through the entire nodes of an if_ixml_document. which is the best way to do this?

Please find the sample document.

<text>
    <id>
         <guid auto="false">
               432543254543
         </guid>
    </id>
     <title>
         <short_title italics="on">
                <bold language = "german">
                     "Hello"
               </bold>
        </short_title>
     </title> </text>

In this document, i need to traverse through the nodes <text>, <id>, <guid> , <title>, <short_title>, <bold> etc.

Thanks in advance

Regards, Alex

Answer

mydoghasworms picture mydoghasworms · Oct 4, 2011

The first step is to parse your XML as follows. You can of course upload the XML from a file into the string, but this is just an example:

data: lr_xml type ref to cl_xml_document.
data: lr_node type ref to if_ixml_node.
data: lv_xml type string.

lv_xml = '<text> <id> <guid auto="false"> 432543254543 </guid> </id> <title> <short_title italics="on"> <bold language = "german"> "Hello"</bold> </short_title> </title> </text>'.

create object lr_xml.

lr_xml->parse_string( lv_xml ).
lr_node = lr_xml->get_first_node( ).

Now you have an instance of IF_XML_NODE that points to the root of your XML document. You can now use the various methods to traverse the XML tree, and get values out of it, using the various methods such as GET_CHILDREN, GET_ATTRIBUTES, GET_NAME etc.

This will be OK for fairly small XML documents, though for efficiency, if you are looking for a specific set of nodes, you may want to look at using an XPATH query.