From: Ryan Leavengood Date: 2005-05-02T03:46:58+09:00 Subject: Re: parsing xml documents using rexml Derek wrote: > Hi, > > I'm new to ruby. > I want to use ruby to process an xml file. > > At the moment I am using the REXML but are open to other xml parsers. > > In the xml file below how would I go about processing the section
in the following way: - > - when the tag is detected perform a method "copy". within the "copy" method extract other child tags within the current element. > - when the tag is detected perform a method "mkdir". within the "mkdir" method extract other tags within the current element. > > I've looked at using XPATH, and have been able to extract specific information but have not worked out how to do it. Here is a somewhat sloppy version, but it works: CODE_BEGIN require 'rexml/document' include REXML def copy(source, target) puts "Copying from #{source} to #{target}" end def mkdir(dir) puts "Making directory #{dir}" end xml_file = ARGV[0] || 'filegroup.xml' doc = Document.new File.new(xml_file) doc.elements.each('fileGroup/details') do |element| element.each do |command| if command.kind_of? Element case command.name when 'copy' source = '' target = '' command.each do |param| if param.kind_of? Element if param.name == 'source' source = param.text elsif param.name == 'target' target = param.text end end end copy(source, target) when 'mkdir' mkdir(command.text) else puts "Unknown command: #{command.name}" end end end end CODE_END If you used attributes instead of subtags it would be easier: CODE_BEGIN doc.elements.each('fileGroup/details') do |element| element.each do |command| if command.kind_of? Element case command.name when 'copy' copy(command.attributes['source'], command.attributes['target']) when 'mkdir' mkdir(command.attributes['dir']) else puts "Unknown command: #{command.name}" end end end end CODE_END Ryan Leavengood