Ryan Leavengood
5/1/2005 6:47:00 PM
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 <details> in the following way: -
> - when the tag <copy> is detected perform a method "copy". within the "copy" method extract other child tags within the current <copy> element.
> - when the tag <mkdir> is detected perform a method "mkdir". within the "mkdir" method extract other tags within the current <mkdir> 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:
<copy source="something" target="whatever"/>
<mkdir dir="some_dir"/>
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