Show TOC Anfang des Inhaltsbereichs

Hintergrunddokumentation Traversing the DOM tree with iterators  Dokument im Navigationsbaum lokalisieren

The previous section showed the DOM Level 1 approach to traversing the DOM tree of an XML document. The DOM Level 2 Working Draft of the W3C introduces the concept of iterators into the realm of the Document Object Model.

Iterators have three especially nice features when used with the DOM:

...

       1.      They provide a consistent interface for access to very different data structures

       2.      They allow to hide the internal workings of the data structures they work on

       3.      By doing so they allow to implement iterator-internal optimizations to utilize specific aspects of the data structure over which they iterate

The DOM Level 2 - and iXML - adds iterators to the following data structures:

·         cl_ixml_node

·         cl_ixml_node_list

·         cl_ixml_node_collection

·         cl_ixml_named_node_map

Iterating over the complete DOM-tree

To traverse the complete DOM-tree in an DFS (Depth-First-Search) traversal, you can use an iterator created on an cl_ixml_document object. If you want to iterate over any sub-tree of the document, simply create the iterator on the root node of the sub-tree over which you want to iterate.

Once you have obtained the iterator, you can repeatedly call the if_ixml_node_iterator::get_next() method until null is returned, which signals the iteration has come to an end.

data: iterator type ref to if_ixml_node_iterator,

      node     type ref to if_ixml_node.

iterator = document->create_iterator( ).

node = iterator->get_next( ).

while not node is initial.

* do something with the node

  ...

  node = iterator->get_next( ).

endwhile.

Sometimes you want to restrict the depth of the traversal. You can do so by passing the factory method of an iterator an additional depth parameter as in the following example, which will only iterate the level immediately below an cl_ixml_element instance.

data: iterator type ref to if_ixml_node_iterator.

iterator = element->create_iterator( 1 ).

Iterating over a list of child nodes

As mentioned before you can create an iterator for all data structures in the iXML implementation. Therefore, an iterator for a node's child nodes is available, as the following code fragment illustrates:

data: nodes type ref to if_ixml_node_list,

      iterator type ref to if_ixml_node_iterator,

      node     type ref to if_ixml_node.

nodes = element->get_children( ).

iterator = nodes->create_iterator( ).

* iterator code as usual:

node = iterator->get_next( ).

while not node is initial.

* do something with the node

  ...

  node = iterator->get_next( ).

endwhile.

Iterating over other data structures

Iterating the other DOM data structures like cl_ixml_named_node_maps works exactly the same as in the cl_ixml_node_listexample above. I will therefore skip it.

Ende des Inhaltsbereichs