Walk an XML file using REXML

# walk an xml file
 
require 'rexml/document'
require 'pp'
 
include REXML
 
def dumpElement(elem, indent)
    newindent = indent * 2
    puts "#{indent}#{elem.name} : #{elem.size}"
    if (elem.class == Element && elem.has_attributes?) then
        elem.attributes.each { |n,v|
            puts "#{newindent}(ATTR)#{n} = #{v}"
        }
    end
    if (elem.class == Element && elem.has_text?) then
        puts "#{newindent}(TEXT)#{elem.get_text.value.chomp}"
    end
    if (elem.class == Element && elem.has_elements?) then
        elem.elements.each {|e|
            dumpElement(e, indent)
        }
    end
end
 
def walkAFile(fil)
    doc = Document.new File.new(fil)
    root = doc.root
    puts "#{root.name} : #{root.size}"
    indent = "  "
    if (root.class == Element && root.has_text?) then
        puts "#{indent}(TEXT)#{root.get_text.value.chomp}"
    end
    if (root.class == Element && root.has_attributes?) then
        root.attributes.each { |n,v|
            puts "#{indent}(ATTR)#{n} = #{v}"
        }
    end
    if (root.class == Element && root.has_elements?) then
        root.elements.each { |e|
            puts "#{indent}(ELEM)#{e.name}"
            dumpElement(e, indent)
        }
    end
end
 
if (ARGV.empty?) then
    STDERR.puts "Need XML filename"
    exit -1
end
 
ARGV.each { |arg|
    print "Testing #{arg}"
    if (File.exists?(arg)) then
        puts " found "
        walkAFile(arg)
    else
        puts " not found"
    end
}

rexmlwalk.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