From: Rob Burrowes Date: 2006-05-20T18:04:41+09:00 Subject: Re: Parsing XML into a complete domain object If you just want to walk the tree from any entry point, through all the sub-levels, you can use the standard each_recurse method. #Recurse end to end, printing the tags @doc.elements.each("definitions/src") do |element| print "<", element.name.to_s, ">" element.each_recursive do |childElement| print "<", childElement.name.to_s, ">" end end If you just want the next level of children, but no deeper, I'm not sure what you call. I did this when I played with REXML, and the obvious each_child doesn't give you an REXML::Element. It gives a REXML::Text element at the first iteration, then the next REXML::Element, then another REXML::Text object, etc. Not quite what you want. But adding this to your code will work. module REXML # Visit all children of this node, but don't recurse to their children def each_child_element(&block) self.elements.each {|node| block.call(node) } end end It probably exists in some form in the REXML module, but I can't find it, so I recreated it (by a little hacking of the modules each_recurse). You can then #printing the tags of the immediate children. @doc = Document.new(File.new(format_file)) @doc.elements.each("definitions") do |element| element.each_child_element do |childElement| print "<", childElement.name.to_s, ">" end end or recursively walk the tree by calling each_child_element for each returned childElement (as with the first example) def recurse(the_element) the_element.each_child_element do |childElement| print "<", childElement.name.to_s, ">" recurse(childElement) end end @doc.elements.each("definitions/src") do |element| recurse(element) end On 20/05/2006, at 9:06 AM, 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. > > It seems that if i try to use any iterators on a root.elements[] > object > it converts it to text so i can't nest another iterator or loop to > access the innards. > > my only recourse has been to resort to a ton of nested while loops > which > is ugly when compared to most other ruby loops. > > eg. > i = 1 > while root.elements['cases'].elements[i] != nil > > n = 1 > while root.elements['cases'].elements['test-case'] != nil > > #more loops here. continue down the chain until i can build the > #object from the inside out. > > i = i+i > end > > i = i+i > end > > > > my xml looks like this > > > somehow i have to get THAT modeled into an object > script object contains test-cases, test-cases contain test-steps > etc.... > > Any thoughts? (sorry for the long post... its kinda hard to explain > without showing EVERYTHING. > > -- > Posted via http://www.ruby-forum.com/. >