On Fri, 2006-05-19 at 23:06, Brian Cowdery wrote:
> Recently at work we've decided to attempt to build a basic XML driven 
> automation framework to work with Watir (a web development testing 
> library for ruby).
> 
> I cant figure out how to loop through each level of the REXML document 
> to extract the data needed to build the complete object.

You might find a treewalker useful:

module XmlUtil
  
  class TreeWalker
    
    def initialize(strategy)
      @strategy = strategy
    end

    def walk(node)
      @strategy.execute_before(node) if @strategy.respond_to?
:execute_before
      if node.instance_of?(REXML::Document)
        walk(node.root)
      elsif node.instance_of?(REXML::Element) then
        node.children.each { |child| 
          walk(child)
        }
      end
      @strategy.execute_after(node) if @strategy.respond_to?
:execute_after
    end
  end
end

The treewalker will walk the XML document, calling the execute_before
and execute_after methods of a strategy object.

You also need a strategy object. The strategy object looks something
like this:

class MyStrategy

  def execute_before(node)
    # Process start tags
    case node
    when REXML::Document :
      # Do nothing with Document nodes.
      # Necessary because Document inherits Element
    when REXML::Element :
      # Do something with the element
    end
  end

  def execute_after(node)
    # Process end tags
  end
end

If the treewalker does not suit your needs, a node iterator (Java Xerces
style) might do the trick. Let me know if you need one. I've got working
code, but the implementation could be more elegant. (One of my first
Ruby classes.)


/Henrik

--
http://kallokain.blogspot.com/ - Blogging from the trenches of software
development
http://www.henrikmartensson.org/  - Reflections on software development
http://tocsim.rubyforge.com/ - Process simulation
http://testunitxml.rubyforge.org/  - XML test framework
http://declan.rubyforge.org/ - Declarative XML processing