require 'rexml/node' require 'rexml/element' require 'rexml/document' require 'rexml/encoding' include REXML #Open an existing XML file. file = File.new("tree.xml","r") doc = REXML::Document.new(file, :ignore_whitespace_nodes => :all) tree = doc.root #print out the attribute 'name' for each leaf node puts "Showing all leafs" XPath.each(doc.root, '//leaf') { |element| #'trunk/bigbranch/smallbranch/leaf' puts element#.text } #find some information about node puts puts "Lets find the node that contains the text leaf8!" node = tree.find_first_recursive() { |node| node.text == 'leaf8' } if(node != nil) puts "index in parent: " + node.index_in_parent().to_s puts "parent: "+ node.parent.attributes['name'] puts "am I a parent?: " + node.parent?.to_s if(node.parent?) puts "I have " + node.size.to_s + " child(ren) :" node.each {|childnode| puts childnode.to_s + ", which is a "+ childnode.class.to_s } end puts "prev sibling node: " + node.previous_sibling_node().text puts "next sibling node: " + node.next_sibling_node().text else puts "could not find leaf8" end #show all the green leafs puts puts "All the green leafs are " tree.each_recursive() { |node| if(node.attributes['color'] == 'green') puts node.text end }