Ruby Xml handling example

# xparse.rb
 
require "rexml/document"
 
if (ARGV.empty?) then
        puts "Need filename"
        exit 1
end
doc = REXML::Document.new File.new(ARGV[0])
doc.elements.each("MetaData/section") { |element| puts element.attributes["name"] }

Alternate example

# xm.rb
 
require "rexml/document"
 
if (ARGV.empty?) then
        puts "Need filename"
        exit 1
end
file = File.new( ARGV[0])
doc = REXML::Document.new file
root = doc.root
puts doc.version
once = 0
root.each { |node|
        if (once == 0) then
                #puts node.methods
                once = 1
        end
        if (node.class == REXML::Element) then
                puts "#{node.to_s} has_attribs: #{node.has_attributes?}"
                puts "#{node.to_s} has_elemes:  #{node.has_elements?}"
 
                if (node.has_elements?) then
                        node.each_element { |e|
                                puts e.get_text
                        }
                end
 
                if (node.has_attributes?) then
                        node.root.each_element_with_attribute('ID') { |e|
                                p e
                        }
                end
        end
 
}

Back to Ruby

rubyxml.txt · Last modified: 2014/10/26 01:52 (external edit)
CC Attribution-Share Alike 3.0 Unported
www.chimeric.de Valid CSS Driven by DokuWiki do yourself a favour and use a real browser - get firefox!! Recent changes RSS feed Valid XHTML 1.0