From: William James Date: 2005-01-25T12:25:51+09:00 Subject: Re: is my installation not working? Boris Glawe wrote: > Hi, > > I am trying to parse an xml file on my fedora Core 3 machine. > I started with a tutorial from this site: > http://www.germane-software.com/software/rexml/docs/tutorial.html If all you need is minimal xml parsing, try this: .. class String .. def get_attr .. s = self .. h = Hash.new .. while s =~ /(\w+)="([^"]*)"/m .. h[ $1 ] = $2 .. s = $' .. end .. h .. end .. .. def span( tagname ) .. s = self .. while (s =~ Regexp.new( .. '(<'+tagname+'.*?>)(.*?)', .. Regexp::MULTILINE)) .. yield( $1, $2 ) .. s = $' .. end .. end .. end .. .. s = '' .. $<.each_line {|x| s=s+x} .. s.span('section') { |tag,text| .. puts "Section: " + tag.get_attr['name'] .. text.span('item') { |tag,text| .. a = tag.get_attr .. puts " Item: upc=#{a['upc']} stock=#{a['stock']}" .. text.span('name') { |tag,name| .. puts " Name: " + name .. } .. text.span('price') { |tag,price| .. puts " Price: " + price .. } .. } .. } With this input:
Invisibility Cream 14.50 Makes you invisible Levitation Salve 23.99 Levitate yourself for up to 3 hours per application
Blork and Freen Instameal 4.95 A tasty meal in a tablet; just add water Grob winglets 3.56 Tender winglets of Grob. Just add water
the output is .. Section: health .. Item: upc=123456789 stock=12 .. Name: Invisibility Cream .. Price: 14.50 .. Item: upc=445322344 stock=18 .. Name: Levitation Salve .. Price: 23.99 .. Section: food .. Item: upc=485672034 stock=653 .. Name: Blork and Freen Instameal .. Price: 4.95 .. Item: upc=132957764 stock=44 .. Name: Grob winglets .. Price: 3.56